When to use prom.all ()?

It is rather a conceptual question. I understand the Promise design template, but could not find a reliable source to answer my question about promise.all():

What is (is) the correct script to use promise.all()

OR

Are there any recommendations for use promise.all()? Should it be ideally used only if all promise objects are of the same or similar types?

The only thing I could think of:

  • Use promise.all()if you want to resolve the promise only if all objects of the promise are allowed and rejected, even if one rejects.
+4
source share
8

, - Promise.all() ( ):

() prom.all()

Promise.all() , , , , promises , . , . , promises, , , Promise.all() , .

, , API, API, , . Promise.all(). - :

Promise.all([apiRequest(...), apiRequest(...), apiRequest(...)]).then(function(results) {
    // API results in the results array here
    // processing can continue using the results of all three API requests
}, function(err) {
    // an error occurred, process the error here
});

Promise.all(), , ( ), , . , API, , , , , Promise.all():

Promise.all([apiRequest(...), fs.readFileAsync(...), readTemperature(...)]).then(function(results) {
    // all results in the results array here
    // processing can continue using the results of all three async operations
}, function(err) {
    // an error occurred, process the error here
});

, , async , Promise.all(). async .then(), .

, Promise.all() " ". , , , , , , promises . , Promise.all(), . , , , . Promise.all() . , , - Promise.settle() . .settle() , , . , , , , , , .

- prom.all()? , ?

, , . , , .


, Promise.all():

  • async. .then() Promise.all().
  • .
  • . , , Promise.all() . , - Promise.settle().
  • promises, Promise.all() async, .
+18

, , , , , API- . , Promises , , anti-patterns.

() prom.all()

, promises.

- prom.all()? , ?

, .

+2

promise.all(), API, - , , , .

:

. (, ), .

API, promises promise.all()

, . , promises.all(), .

, , promises.all()

+1

Promise.all Promises ( ). , , Promises:

// p1, p2, p3 are Promises
Promise.all([p1, p2, p3])
  .then(([p1Result, p2Result, p3Result]) => {
    // This function is called when p1, p2 and p3 have all resolved.
    // The arguments are the resolved values.
  })

- Promises , Promise, Promise.all, .

API, :

 const contentPromise = requestUser();
 const commentsPromise = requestComments();

 const combinedContent = Promise.all([contentPromise, commentsPromise])
   .then(([content, comments]) => {
     // content and comments have both finished loading.
   })

Promise.all Promise.

+1

Promise.all- , Promise.all(iterable) , , promises , .

2. Promise.all().catch(err = > {}) , ANY promises.

3.Use.reflect promises .all, promises

  1. -Promise.all(iterable);
0

:

myService.getUsers()
   .then(users => {
       this.users = users;

       var profileRequests = users.map(user => {
           return myService.getProfile(user.Id); // returns a promise
       });

       return Promise.all(profileRequests);
   })
   .then(userProfilesRequest => {
       // do something here with all the user profiles, like assign them back to the users.

       this.users.forEach((user, index) => {
           user.profile = userProfilesRequest[index];
       });
   });

. , - , x promises.

, Promise.all() promises , then. , , , .. .. , promises, .

0

Promise.all promises , .

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

var isCallFailed = false;
function myEndpoint1() {
  return isCallFailed ? Promise.reject("Bohoo!") :Promise.resolve({"a":"a"});
}
function myEndpoint2() {
  return Promise.resolve({"b":"b"});
}

Promise.all([myEndpoint1(), myEndpoint2()])
.then(values => {
  var data1 = values[0];
  var data2 = values[1];
  alert("SUCCESS... data1: " + JSON.stringify(data1) + "; data2: " +  JSON.stringify(data2));
})
.catch(error => {
  alert("ERROR... " + error);
});

, isCallFailed = true.

0

Promise.all, Promise.all

( "" ) - .

Promise - , . ( "" ), - : ( " " ) ( " " ).

:

  • unFulfilled - , "" ".
  • - , " ".

:

var promise = new Promise(function(resolve, reject) {
  // This function will be called automatically

  // It is possible to make any asynchronous operations,
  // And when they will end - you need to call one of:
  // resolve(result) on success
  // reject(error) on error
})

:

promise.then(onFulfilled, onRejected)
  • onFulfilled - , .

  • onRejected - , .

, :

// onFulfilled It works on success
promise.then(onFulfilled)
// onRejected It works on error
promise.then(null, onRejected)

- ,

'use strict';

let p = new Promise((resolve, reject) => {
  //    reject(new Error("o_O"))
  throw new Error("o_O");
});

p.catch(alert); // Error: o_O

Promisification Promisification - PROMIS.

Promisification .

XMLHttpRequest

httpGet (url) PROMIS, URL , - :

function httpGet(url) {

    return new Promise(function(resolve, reject) {

        var xhr = new XMLHttpRequest();
        xhr.open('GET', url, true);

        xhr.onload = function() {
            if (this.status == 200) {
                resolve(this.response);
            } else {
                var error = new Error(this.statusText);
                error.code = this.status;
                reject(error);
            }
        };

        xhr.onerror = function() {
            reject(new Error("Network Error"));
        };

        xhr.send();
    });

}

, XMLHttpRequest , , onload/onerror, , ( 200) .

:

httpGet("/article/promise/user.json")
    .then(
        response => alert(`Fulfilled: ${response}`),
        error => alert(`Rejected: ${error}`)
    );

, ?

Promise .

Promise.all()

Call Promise.all(iterable) ( ) PROMIS PROMIS, , PROMIS , "done" .

:

Promise.all([
    httpGet('/article/promise/user.json'),
    httpGet('/article/promise/guest.json')
]).then(results => {
    alert(results);
});

, URL.

let urls = [
  '/article/promise/user.json',
  '/article/promise/guest.json'
];

, :

  • URL-, PROMIS.
  • PROMIS Promise.all.

:

' strict';

let urls = [
  '/article/promise/user.json',
  '/article/promise/guest.json'
];

Promise.all( urls.map(httpGet) )
  .then(results => {
    alert(results);
});

, - ,

Promise. .

PROMIS .

:

Promise.all([
    httpGet('/article/promise/user.json'),
    httpGet('/article/promise/guest.json'),
    httpGet('/article/promise/no-such-page.json') // (  )
]).then(
    result => alert(" "),
    error => alert(": " + error.message) // : Not Found
)

:

  • Promise - , , ( ) .
  • Promise ((, ) = > ...) , () () - .
  • / ( , ) .
  • .then/catch.
  • Channing.

https://www.promisejs.org/patterns/

-3

All Articles