有以下代码...
const array = [
Promise.resolve(1), Promise.resolve(2), Promise.resolve(3)
];
Array.prototype.then = function () {
console.log('Why does this gets triggered?');
}
Promise.all(array)
.then(result => console.log(result))
为什么
Promise.all()
自己调用我的
.then()
数组上的proto函数?
当然必须调用
.then()
对于数组中的每个元素。这很明显。但是在 Array 本身上这样做的目的是什么?
这种行为发生在 V8 上
考虑:如果您更改
Promise.all()
至
Promise.race()
这不会发生。
我不是说这是一个错误。我只是想了解原因。如果您可以在答案中引用 EcmaScript 规范,我将不胜感激。
更新:
我知道
Promise.all()
返回一个数组,但包装在一个 promise 上。这也很明显。如果您删除
.then()
喜欢...
Promise.all(array)
它仍然执行
.then()
方法。
请您参考如下方法:
当一个 resolve()
被调用,并且传递给它的值有 .then
引用函数的属性,正常的 Promise 机制将调用该函数。在这种情况下,Promise.all()
内部当源数组中的每个 Promise 被解析时,就会构建一个分辨率值数组。完成后,Promise.all()
的内脏将调用它自己的resolve()
,传入解析值数组。
那么该数组也将有一个 .then()
值,继承自 Array 原型(prototype)。因此 resolve()
调用将调用 .then()
方法就像任何其他 Promise 解决方案一样。
Promise resolve()
in the spec