为什么Promise.all()允许非Promise对象?

时间:2017-04-04 21:39:49

标签: promise es6-promise

为什么Promise.all()允许任何对象作为可迭代传递?

示例(jsfiddle:https://jsfiddle.net/npqgpcud/6/):

var promise1 = "one";
var promise2 = 2222;
var promise3 = new Promise(function (fulfill, reject) {
    fulfill("three");
});

Promise.all([promise1, promise2, promise3]).then(results => {
    p1.innerHTML = results[0];
    p2.innerHTML = results[1];
    p3.innerHTML = results[2];
});

如果我想模仿单一承诺的这种行为,是否有推荐的解决方案或建议使用Promise.all([promise])?

1 个答案:

答案 0 :(得分:1)

一个值的等价物是Promise.resolve()

您可以传递承诺或其他价值。后者将立即用该值解决承诺。

一些例子:



const wait = ms => new Promise( resolve => setTimeout(resolve, ms) );

console.log('start');
Promise.resolve(wait(1000)).then( _ => console.log('done') );
Promise.resolve(42).then( data => console.log(data) );
Promise.resolve(Promise.reject('oh no')).catch( data => console.log(data) );




Promise.all([one value])唯一的区别是,它仍会产生一个值的数组。

查看显示的已解决值(42)的细微差别:



const wait = ms => new Promise( resolve => setTimeout(resolve, ms) );

console.log('start');
Promise.all([wait(1000)]).then( _ => console.log('done') );
Promise.all([42]).then( data => console.log(data) );
Promise.all([Promise.reject('oh no')]).catch( data => console.log(data) );