简体   繁体   中英

Sequential function calls

I have an array of asynchronous functions, it is necessary to call in order and the result of the call of the previous function is passed into the arguments. How can this be done approximately?

// lets say we have a function that takes a value and adds 20 to it asynchronously
const asyncPlus20 = num => Promise.resolve(num+a)
const arr = [asyncPlus20, asyncPlus20]

let res = 0 // some starting value
for (const f of arr) res = await f(res)
// res is now 20

One of the best way for Array of Async functions is to use For...of .

Run the below snippet in the console. >> Also includes the argument passing

const twoSecondsPromise = () => {
    return new Promise((resolve) => {
        setTimeout(() => resolve('2000_'), 2000);
    })
};

const threeSecondsPromise = (val) => {
    return new Promise((resolve) => {
        setTimeout(() => resolve(val + '3000_'), 3000);
    })
};

const fiveSecondsPromise = (val) => {
    return new Promise((resolve) => {
        setTimeout(() => resolve(val + '5000_'), 5000);
    })
};

(async function () {
    const asyncFunctions = [twoSecondsPromise, threeSecondsPromise, fiveSecondsPromise];
    let result;
    for (const file of asyncFunctions) {
        result = await file(result);
        console.log(result);
     }
})();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM