inu1255
4/28/2018 - 8:58 AM

promise_flow.js

/**
 * 按顺序执行Promise
 * @param {Array<(ret:Any,i:Number,brk:()=>)=>Promise>} tasks 
 * @param {Any} [init]
 * @returns {Promise}
 */
function flow(tasks, init) {
    return new Promise((resolve, reject) => {
        var i = 0;
		var ret = init;
		var brk = false;

        function next(data) {
            ret = data;
            i++;
            if (brk || i < tasks.length)
                tasks[i](ret, i).then(next, reject).catch(reject);
            else
                resolve(ret);
        }
        tasks[i](ret, i, ()=>brk=true).then(next, reject).catch(reject);
    });
};