Home >Web Front-end >JS Tutorial >How to Achieve Synchronous Execution of Promise Loops while Preserving Order?

How to Achieve Synchronous Execution of Promise Loops while Preserving Order?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-29 14:01:02680browse

How to Achieve Synchronous Execution of Promise Loops while Preserving Order?

Achieving Synchronous Execution of Promise Loops

How do you ensure the synchronicity of promise calls and their chained logging operations during loop iterations? The initial approach using promiseWhile() seems promising but raises concerns about preserving the proper execution order.

Instead, consider leveraging the inherent capabilities of promises for this task. By defining the problem as a series of asynchronous calls to fetch user details and maintain the original response order, we can utilize Array.prototype.reduce() to construct a flat .then() chain.

Solution:

The following code exemplifies this 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 function takes an array of email addresses and returns a Promise. The reduce() function iterates through the array and executes the getUser promise for each email. The results are logged synchronously in the done() callback.

Calling the Function:

To call the function, populate an array of email addresses (arrayOfEmailAddys) and use it as follows:

<code class="javascript">fetchUserDetails(arrayOfEmailAddys).then(function() {
    console.log('all done');
});</code>

This code creates a linear promise chain, ensuring that each promise is resolved sequentially and the logging operations execute in the correct order.

The above is the detailed content of How to Achieve Synchronous Execution of Promise Loops while Preserving Order?. 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