Promise循环串行执行写法

需求是有一个objects数组,其中的元素是每次异步事件需要的参数
异步事件事件接受参数并且串行执行,最终返回一个promise结果

Promise.all似乎是并行的?

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);
    });
};

这样写似乎也是并行的?


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

// 测试结果为
// 直接打印了“成功” data为undefined 之后 一次性打印出所有“number”
// 而不是 每隔2s打印一个number number都打印完后 打印成功 并且data应给是个number数组

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("成功");
        console.log(data);
    }).catch((err) => {
        console.log("失败");
        console.log(err)
    });   

两种写法貌似有有问题呢

到是用async/await实现了
虽然不知道对不对啊 但是实现了预期

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

    return result;
};

请问用Promise实现这种逻辑的正确的写法是怎么样的?求解!谢谢!!!

阅读 15.7k
2 个回答

第二种方式的正确的

http://runjs.cn/code/ilckwwjy

如果需要返回结果的话, 可以再加一层 Promise

const list = [];
for (let i = 0; i < 100; ++i) {
    list.push(i);
}
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("成功");
    console.log(data);
}).catch((err) => {
    console.log("失败");
    console.log(err)
}); 
function sequence(promises, cb, ...args) {
    const p = Promise.resolve(),
        len = promises.length
    if (len <= 0) {
        return p
    }
    let i = 0
    //如果cb不是函数
    if (typeof cb !== 'function') {
        cb = null
        args = [cb, ...args]
    }

    function callBack(...params) {
        return p.then(r => {
            return promises[i](r, ...params)
        }).then(r => {
            ++i
            cb && cb(r, i, ...params)
            return i > len - 1 ? Promise.resolve(r) : callBack(...params)
        })
    }

    return callBack(...args)
}


var list = [];
for (let i = 0; i < 5; ++i) {
    list.push(i);
}

sequence(list.map( number=>{
    
      return  _ => new Promise((resolve, reject) => {
            setTimeout(() => {
                console.log(number);
                return resolve(number);
            }, 100);
        })
})).then((data) => {
        console.log("成功");
        console.log(data);
    }).catch((err) => {
        console.log("失败");
        console.log(err)
    });  
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏