Correct way to write loops for promise.

后端 未结 13 1718
猫巷女王i
猫巷女王i 2020-11-22 15:20

How to correctly construct a loop to make sure the following promise call and the chained logger.log(res) runs synchronously through iterat

13条回答
  •  孤街浪徒
    2020-11-22 15:50

    Here's another method (ES6 w/std Promise). Uses lodash/underscore type exit criteria (return === false). Note that you could easily add an exitIf() method in options to run in doOne().

    const whilePromise = (fnReturningPromise,options = {}) => { 
        // loop until fnReturningPromise() === false
        // options.delay - setTimeout ms (set to 0 for 1 tick to make non-blocking)
        return new Promise((resolve,reject) => {
            const doOne = () => {
                fnReturningPromise()
                .then((...args) => {
                    if (args.length && args[0] === false) {
                        resolve(...args);
                    } else {
                        iterate();
                    }
                })
            };
            const iterate = () => {
                if (options.delay !== undefined) {
                    setTimeout(doOne,options.delay);
                } else {
                    doOne();
                }
            }
            Promise.resolve()
            .then(iterate)
            .catch(reject)
        })
    };
    

提交回复
热议问题