The original link https://segmentfault.com/q/1010000007499416 】

【 Note 】 The original article is a question and answer form of the post, here has done a small amount of collation; This article is transferred here for my collection and convenient search. If there is infringement, please contact to delete.

The requirement is to have an array of objects whose elements are the parameters required for each asynchronous event. The asynchronous event takes the parameters and executes them sequentially, eventually returning a promise

Promise.all seems to be parallel?

const PromiseForEach = (objects, asyncDosometing) => {
    return new Promise((resolve, reject) => {
        Promise.all(objects.map((obj) => {
            return new Promise((resolve, reject) => {
                return asyncDosometing(obj).then(resolve, reject);
            });
        })).then(resolve, reject);
    });
};
Copy the code

It’s kind of parallel, right?

const PromiseForEach = (objects,asyncDosometing) => {
        let result = Promise.resolve();
        objects.forEach((obj) => {
            result = result.then(asyncDosometing(obj));
        });
        return result;
    }
Copy the code

// The result of the test is // print all “numbers” at once after the data is undefined // instead of printing the number every 2s, print the number successfully after the number is printed and the data should be an array of numbers

const list = [];
    for (let i = 0; i < 100; ++i) {
        list.push(i);
    }
    PromiseForEach(list, (number) => {

        return new Promise((resolve, reject) => {
            setTimeout(() => {
                console.log(number);
                return resolve(number);
            }, 2000);
        })

    }).then((data) => {
        console.log("Success");
        console.log(data);
    }).catch((err) => {
        console.log("Failure");
        console.log(err)
    });   
Copy the code

Async /await = async/await = async/await = async/await

const PromiseForEach = async(objects, asyncDosometing) => {
    let result = [];
    for (let obj in objects) {
        try {
            result.push(await asyncDosometing(obj));
        } catch (err) {
            returnerr; }}return result;
};
Copy the code

What is the correct way to implement this logic with Promise? To solve! Thanks!!

Here are people from the communitywhbbAnswer:

The second way the correct runjs.cn/code/ilckww… If you need to return results, you can add another layer of Promise

const list = [];
for (let i = 0; i < 100; ++i) {
    list.push(i);
}
Copy the code
function PromiseForEach(arr, cb) {
    let realResult = []
    let result = Promise.resolve()
    arr.forEach((a, index) => {
        result = result.then(() => {
            return cb(a).then((res) => {
                realResult.push(res)
            })
        })
    })

    return result.then(() => {
        return realResult
    })
}

PromiseForEach(list, (number) => {

    return new Promise((resolve, reject) => {
        setTimeout(() => {
            console.log(number);
            return resolve(number);
        }, 100);
    })

}).then((data) => {
    console.log("Success");
    console.log(data);
}).catch((err) => {
    console.log("Failure");
    console.log(err)
}); 
Copy the code

Here are some of the motley crew

  • When I first started using promises, I couldn’t figure out how to use promises to control asynchrony inside a for loop and get an asynchronous result array outside the loop.
  • Until I saw thisQuestion and answerAnd sawlet result = Promise.resolve()This way, I am bright. Use a Promise object to pass the result of the asynchronous task’s completion as a parameter, and then push the result into a global array to get the result.
result = result.then(() => {
            return cb(a).then((res) => {
                realResult.push(res)
            })
        })
Copy the code
  • All right, enough.) (> _ <