logo

JavaScript Promise all() metode

The Promise.all() metode faktiski ir solījuma objekta metode (kas ir arī objekts zem JavaScript, ko izmanto visu asinhrono darbību apstrādei), kas izmanto solījumu masīvu (atkārtojamu) kā ievadi. Tas atgriež singlu Apsolīt kas tiek atrisināts, kad visi solījumi ir nodoti atkārtojuma veidā, kas ir atrisināti, vai ja iterable nesatur solījumus. Vienkāršā veidā, ja kāds no nodotajiem solījumiem tiek noraidīts, Promise.all() metode asinhroni noraida jau noraidītā solījuma vērtību neatkarīgi no tā, vai citi solījumi ir izpildīti.

Sintakse:



Promise.all( iterable )>

Parametri: Šī metode pieņem vienu parametru atkārtojams kas aizņem masīvu solījumi vai parasts masīvs, kurā ir daži objekti.

Atgriešanas vērtības: Lai atgrieztu vienu solījumu, jāievēro daži noteikumi:

  • Ja pieņemtais arguments ir tukšs, tas atgriež solījumu, kas jau ir atrisināts .
  • Ja nokārtotajā atkārtojumā nav solījumu, tas atgriež solījumu, kas ir atrisināts asinhroni .
  • Visos citos gadījumos tas atgriež neapstiprinātu solījumu.

Promise.all() metodes izpilde un noraidīšana:



Izpilde: Atdotais solījums ir izpildīts,

  • Ja nokārtotā iterable ir tukša, šī metode sinhroni atgriež solījumu, kas jau ir atrisināts.
  • Ja tiek izpildīti visi dotie solījumi, atdotie solījumi tiek pildīti asinhroni.
  • Šeit šīs konkrētās metodes veiksmīga izpilde ir pilnībā atkarīga no visiem solījumiem, lai tā tiktu veiksmīgi izpildīta.

Noraidīšana: Ja kāds no dotajiem solījumiem tiek noraidīts, tad šī metode noraida šī solījuma vērtību neatkarīgi no tā, vai citi solījumi ir izpildīti vai nav. Citiem vārdiem sakot, ja kādu solījumu neizdodas izpildīt, tad Promise.all() metode atgriezīs kļūdu un neņems vērā, vai citi solījumi tiek veiksmīgi izpildīti vai nē.

Tālāk minētie piemēri ilustrē JavaScript Promise.all() metodi:



1. piemērs: Promise.all() metode gaida izpildi

javascript




bezmaksas vs bezmaksas
p1 = Promise.resolve(50);> p2 = 200> p3 =>new> Promise(>function> (resolve, reject) {> >setTimeout(resolve, 100,>'geek'>);> });> Promise.all([p1, p2, p3]).then(>function> (values) {> >console.log(values);> });>

>

>

java masīvu saraksta metodes
Izvade

[ 50, 200, 'geek' ]>

2. piemērs: Šeit Promise.all() metode tiek atrisināta pēc 2000 ms, un izvade tiek parādīta kā masīvs.

javascript




// Simple promise that resolves> // after a given time> const tOut = (t) =>{> >return> new> Promise((resolve, reject) =>{> >setTimeout(() =>{> >resolve(`Completed>in> ${t}`)> >}, t)> >})> }> // Resolving a normal promise> tOut(1000).then(result =>console.log(result +>' '>))> // Completed in 1000> // Promise.all> Promise.all([tOut(1000), tOut(2000)])> >.then(result =>console.log(result))>

>

>

Izvade:

Completed in 1000 Completed in 1000, Completed in 2000>

Šeit, Promise.all() metode ir izpildīto solījumu secība. Pirmais solījums masīvā tiks atrisināts līdz pirmajam izvades masīva elementam, otrais solījums būs otrais elements izvades masīvā, un tā tālāk.

3. piemērs: Šeit ir , uz Promise.all() metode gaida, līdz visi solījumi tiks atrisināti.

javascript




// Simple promise that resolves after a given time> const tOut = (t) =>{> >return> new> Promise((resolve, reject) =>{> >setTimeout(() =>{> >resolve(`Completed>in> ${t}`)> >}, t)> >})> }> // Array contains some time duration> const durations = [1000, 2000, 3000]> const promises = []>// Empty array> durations.map((duration) =>{> >// Calling the async function timeout(), so> >// at this point the async function has started> >// and enters the 'pending' state> >// pushing the pending promise to an array.> >promises.push(tOut(duration))> })> console.log(promises)> // Passing an array of pending promises to Promise.all> // Promise.all will wait till all the promises get resolves> // and then the same gets resolved.> Promise.all(promises).then(response =>console.log(response))> // It prints after previous promises gets resolved> // ['Completed in 1000', 'Completed in 2000', 'Completed in 3000']>

kā pārbaudīt ekrāna izmēru

>

>

Izvade:

[object Promise], [object Promise], [object Promise] . . . (gap between previous and last promises) . . Completed in 1000, Completed in 2000, Completed in 3000>

4. piemērs: Kā parādīts šajā piemērā, ja viens no solījumiem neizdodas, visi pārējie solījumi neizdodas un rezultāts tiks parādīts konsolē kļūdas formā. Tad Promise.all() metode tiek noraidīta.

javascript




// Promise that resolves after a given time> const tOut = (t) =>{> >return> new> Promise((resolve, reject) =>{> >setTimeout(() =>{> >if> (t === 2000) {> >reject(`Rejected>in> ${t}`)> >}>else> {> >resolve(`Completed>in> ${t}`)> >}> >}, t)> >})> }> const durations = [1000, 2000, 3000]> // Array contains some time durations> const promises = []>//empty array> durations.map((duration) =>{> >promises.push(tOut(duration))> >// Pushing durations in the promises array> })> // Passing an array of pending promises to Promise.all> Promise.all(promises).then(response =>console.log(response))> >// Promise.all cannot be resolved, as one of the> >// promises passed, got rejected.> >.>catch>(error =>console.log(`::Error:: ${error}`))> // Promise.all throws an error.>

>

ko nozīmē xdxd
>

Izvade:

Error Rejected in 2000>

5. piemērs: Šajā piemērā mēs izmantosim kādu taimera funkciju (īpaši funkciju setTimeout), kurā ir dažādi taimeri, un tie tiks ierakstīti dažādos solījumos, un tālāk šie solījumi tiks nodoti Promise.all() metožu ietvaros, lai iegūtu rezultātu.

Javascript




let first_promise =>new> Promise((resolve, reject) =>{> >setTimeout(() =>{> >resolve(>'Resolved First after 1 second'>);> >}, 1000);> });> let second_promise =>new> Promise((resolve, reject) =>{> >setTimeout(() =>{> >resolve(>'Resolved First after 2 seconds'>);> >}, 2000);> });> let third_promise =>new> Promise((resolve, reject) =>{> >setTimeout(() =>{> >resolve(>'Resolved First after 3 seconds'>);> >}, 3000);> });> try> {> >let result = Promise.all([first_promise, second_promise, third_promise]);> >result.then((data) =>console.log(data));> }>catch> (error) {> >console.log(error);> }> // This code is contributed by Aman Singla...>

>

>

Izvade:

[  'Resolved First after 1 second',  'Resolved First after 2 seconds',  'Resolved First after 3 seconds' ]>

Atbalstītās pārlūkprogrammas:

Pārlūkprogrammas, ko atbalsta JavaScript Promise.all() metodes ir uzskaitītas zemāk:

  • Google Chrome 32 un jaunākas versijas
  • Mala 12 un augstāk
  • Firefox 29 un jaunākas versijas
  • Opera 19 un jaunākas versijas
  • Safari 8 un jaunākas versijas
  • Internet Explorer netiek atbalstīts