Making A For Loop Wait Without A Library In Js
How can one create a for loop that waits for an asynchronous call to complete prior to starting a new iteration of a loop WITHOUT a library (like jQuery)? Example: Thanks UPDATE
Solution 1:
You can use reduce to make them process sequentially (or set up the promise chain using a regular for loop -- I prefer reduce, myself).
let promise = items.reduce((carry, current) => {
return carry.then(arr => {
returnasyncAPIcall({ body: current }).then(result => arr.concat([ result ]));
});
}, Promise.resolve([]));
promise.then(finalResult => {
console.log('final result:', finalResult);
});
This may be more than you need, if you don't actually need to capture the results of those promise resolutions, though. Also note that you'll still have a promise at the end of it, which will contain an array of the results of each promise, corresponding to their original array position.
Also, here is a mocked version of the asyncAPIcall
, which should assist with showing the order of operations here, if you want to trace through how / where the methods are called.
functionasyncAPIcall(obj) {
console.log('asyncAPIcall for:', obj);
returnnewPromise((resolve) => {
setTimeout(() => {
let resolution = obj.body + 5; // change the value in some way, just to show that input !== outputconsole.log('resolving with:', resolution);
returnresolve(resolution);
}, 100);
});
}
Post a Comment for "Making A For Loop Wait Without A Library In Js"