Home  >  Article  >  Web Front-end  >  How to Achieve Synchronous Logging When Iterating Through Promises in JavaScript?

How to Achieve Synchronous Logging When Iterating Through Promises in JavaScript?

Barbara Streisand
Barbara StreisandOriginal
2024-10-26 21:43:02428browse

How to Achieve Synchronous Logging When Iterating Through Promises in JavaScript?

Iterating Through Promise Calls with Synchronization

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.

Proposed Solution

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:

  1. Creates an Array of Promises: It accepts an array of email addresses (arr) and composes a sequence of promises based on each email.
  2. Serial Execution with reduce: It leverages Array.prototype.reduce to execute the promises sequentially.
  3. Guaranteed Order: By chaining the promises with then, it ensures that logger.log(res) is invoked only after the previous promise has resolved.

Example Usage

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn