Home >Web Front-end >JS Tutorial >How to Ensure Synchronous Loop Execution with Promise Operations?

How to Ensure Synchronous Loop Execution with Promise Operations?

Linda Hamilton
Linda HamiltonOriginal
2024-11-03 00:13:291088browse

How to Ensure Synchronous Loop Execution with Promise Operations?

Coordinating a Loop with Promises

Problem Statement

How can we ensure that a loop iterates synchronously, executing each iteration's promise and its subsequent logging operation (logger.log(res)) in the correct order?

Solution

Eschewing PromiseWhile

While the promiseWhile function can facilitate looping with promises, it does not guarantee the order of execution for chained operations.

Using Reduce for Serialization

To maintain the desired order, we can leverage Array.prototype.reduce() to create a flat chain of .then() operations. This eliminates the need for recursion.

<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>

Sample Usage

<code class="javascript">// Compose an array of email addresses
var arrayOfEmailAddys = [...];

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

Benefits

This approach eliminates the extra variable and condition function required in the promiseWhile method. Additionally, it simplifies the code and ensures the correct ordering of promise executions.

The above is the detailed content of How to Ensure Synchronous Loop Execution with Promise Operations?. 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