Let's imagine you want to fetch two users from two tokens in parallel and when you have fetched both of them, see if their last names are the same.
Here's an example API call:
function getUser(token) {
return new Promise((resolve, reject) => {
if (token === "james") {
resolve({firstName: "james", lastName: "gardner"});
} else if (token === "bob") {
resolve({firstName: "james", lastName: "gardner"});
} else {
reject(new Error("Invalid token"));
}
});
};
Here's how you do it:
const personJames = getUser("james");
const personBob = getUser("bob");
Promise.all([personJames, personBob]).then(values => {
if (values[0].lastName === values[1].lastName) {
console.log("Same names");
}
});
If any of the individual calls fail, the promise will be rejected.
You can also pass resolved promises or basic types into Promise.all()
.
See also:
Copyright James Gardner 1996-2020 All Rights Reserved. Admin.