Promise.all 不应该作为传递给 .then 的函数工作

Shouldn't Promise.all work as the function passed to .then?

本文关键字:then 函数 工作 all 不应该 Promise      更新时间:2023-09-26

此代码适用于 Chrome(47)、FF(43) 和 Node.js(4.2.2):

Promise.resolve()
.then(function() {
    return new Array(5).fill(Promise.resolve('hello world'));
})
.then(function(promisesArr) {
    return Promise.all(promisesArr);
})
.then(function(allResults) {
    console.log(allResults);
}).catch(function(err) {
    console.log('FAILED: ' + err);
});

然而,第二个 .then 包含一个"无用"的匿名函数(调用具有相同参数的单个函数,返回结果)。

据我了解,这种模式可以而且应该通过直接引用函数本身来替换,如下所示:

Promise.resolve()
.then(function() {
    return new Array(5).fill(Promise.resolve('hello world'));
})
.then(Promise.all)
.then(function(allResults) {
    console.log(allResults);
}).catch(function(err) {
    console.log('FAILED: ' + err);
});

然而,虽然这在FF中有效,但它在Chrome和(可以预见,因为它也基于V8)在Node上失败,分别具有:

失败:类型错误:未定义不是函数

失败:类型错误:_runMicrotasks不是函数

我认为这是一个错误是否正确?还是我的理解是匿名函数可以替换为对要称为不正确的函数的简单引用?

这在很大程度上取决于函数的定义方式。如果函数使用对象的上下文,则需要提供适合该特定上下文的上下文(即 Promise 对象)。

如果函数使用this那么你需要做:

Promise.all.bind(Promise);

但是,如果函数直接使用 Promise 对象,则没关系。不过,为了与其他Promise实现兼容,我仍然会绑定它。