Home >Web Front-end >JS Tutorial >How to Achieve Synchronous Logging When Iterating Through Promises in JavaScript?
A common scenario involves looping through a series of promise calls, such as API requests, to ensure that the order of execution is maintained. Bluebird offers a solution through the promiseWhile function. However, there are concerns about the order of logger.log(res) calls within the loop.
Instead of using promiseWhile, consider the following approach:
<code class="javascript">function fetchUserDetails(arr) { return arr.reduce(function(promise, email) { return promise.then(function() { return db.getUser(email).done(function(res) { logger.log(res); }); }); }, Promise.resolve()); }</code>
This code:
Invoke the fetchUserDetails function with the array of email addresses:
<code class="javascript">// Compose an array of email addresses const arrayOfEmailAddys = [...]; fetchUserDetails(arrayOfEmailAddys).then(function() { console.log('all done'); });</code>
This approach eliminates the need for recursion, external counters, and complex condition functions, while maintaining the desired synchronization of logger.log(res) calls.
The above is the detailed content of How to Achieve Synchronous Logging When Iterating Through Promises in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!