How does this mergePromise method solve this problem?

//mergePromise
//data

const timeout = ms => new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve();
    }, ms);
});

const ajax1 = () => timeout(2000).then(() => {
    console.log("1");
    return 1;
});

const ajax2 = () => timeout(1000).then(() => {
    console.log("2");
    return 2;
});

const ajax3 = () => timeout(2000).then(() => {
    console.log("3");
    return 3;
});


function mergePromise(ajaxArray){
    let arr = [];
    let p = Promise.resolve();
    ajaxArray.forEach(item=>{
        p = p.then(data=>{
            if(data){
                arr.push(data);
            }
            return item();
        });
    })
    return p.then(data=>{
        arr.push(data);
        return arr;
    })
}

mergePromise([ajax1, ajax2, ajax3]).then(data => {
    console.log("done");
    console.log(data); // data  [1, 2, 3]
});

// 
// 1
// 2
// 3
// done
// [1, 2, 3]

what is the principle of this mergePromise?
every time I rewrite p? Promise.resolve?

Apr.11,2021

The return, in the then chain of

promise and the result returned is that a new Promise can be processed by the next then. He takes advantage of this by adding each ajax request to a then chain of a P, which is the beginning of the then chain directly through resolve.

then in forEach p = p.then () is so that the next time forEach can continue to follow the next then chain.

since the processing in the then chain adds the previous result to the array, and then returns the new Promise, this time, you have to add a sentence p.then to the final return to store the result of the last call.

this is an ingenious use of the structure of Promise.

Menu