let locArr = [{ x: 0, y: 0 }, { x: 2, y: 4 }, { x: 6, y: 8 }];
// my asynchronous function that returns a promise
function findLoc(x, y) {
return new Promise((resolve, reject) => {
let a = setTimeout(() => {
resolve({ x: x * x, y: y * y });
}, 500);
});
}
Promise.all([
// my problem is below
findLoc(locArr[0].x, locArr[0].y),
findLoc(locArr[1].x, locArr[1].y),
findLoc(locArr[2].x, locArr[2].y),
]).then(values => {
// all values from all the promises
});
How can I write the Promise.all()
function to take parameters from an array of varying size?
I want to pass arguments to the array of promises accepted in the .all()
method of the Promise
class. What is the best way to do that?
Given an array of Promises, we have to run that in a series. To do this task, we can use then(), to run the next promise, after completion of a promise. Approach: The then() method returns a Promise, which helps us to chain promises/methods.
Using Promise.all()Promise.all waits for all fulfillments (or the first rejection).
The Promise. all() method is actually a method of Promise object (which is also an object under JavaScript used to handle all the asynchronous operations), that takes an array of promises(an iterable) as an input.
As you can see, Promise. all executes code concurrently, but what is parallel execution? JavaScript is single-threaded and can only perform a single chunk of work at a time, so parallel execution is not possible with JavaScript, except for some circumstances such as web workers.
use map
instead
let locArr = [{
x: 0,
y: 0
}, {
x: 2,
y: 4
}, {
x: 6,
y: 8
}];
// my asynchronous function that returns a promise
function findLoc(x, y) {
return new Promise((resolve, reject) => {
let a = setTimeout(() => {
resolve({
x: x * x,
y: y * y
});
}, 500);
});
}
Promise.all(
locArr.map(o => findLoc(o.x, o.y))
).then(values => {
// all values from all the promises
console.log(values)
});
You can use map:
let locArr = [{ x: 0, y: 0 }, { x: 2, y: 4 }, { x: 6, y: 8 }];
// my asynchronous function that returns a promise
function findLoc(x, y) {
return new Promise((resolve, reject) => {
let a = setTimeout(() => {
resolve({ x: x * x, y: y * y });
}, 500);
});
}
Promise.all(
locArr.map(//map location to promise
location=>findLoc(location.x,location.y)
)
).then(values => {
// all values from all the promises
});
This is a trick that requires to modify a little the input of findLoc
:
let locArr = [{ x: 0, y: 0 }, { x: 2, y: 4 }, { x: 6, y: 8 }];
// my asynchronous function that returns a promise
//
function findLoc({x, y}) {
return new Promise((resolve, reject) => {
let a = setTimeout(() => {
resolve({ x: x * x, y: y * y });
}, 500);
});
}
Promise.all(locArr.map(findLoc)).then(values => {
console.log(values);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With