使用 Promise.all 确保异步操作的顺序

2021-11-25  本文已影响0人  前端技师胡帅博
var p1 = new Promise((resolve, reject) => {
    setTimeout(resolve, 2000, 'one');
});
var p2 = new Promise((resolve, reject) => {
    setTimeout(resolve, 1000, 'two');
});
var p3 = new Promise((resolve, reject) => {
    setTimeout(resolve, 4000, 'three');
});
var p4 = new Promise((resolve, reject) => {
    setTimeout(resolve, 3000, 'four');
});

Promise.all([p1, p2, p3, p4]).then(values => {
    for (let i = 0; i < values.length; i++) {
        let v = values[i]
        console.log(v)
    }
}, reason => {
    console.log(reason)
});

// 输出结果:
// one
// two
// three
// four
上一篇下一篇

猜你喜欢

热点阅读