forEach、map、reduce和promise那點事(上)
通過此文,您可以學到:
- forEach、map、reduce 后面能不能帶 async 函數?
- 怎么實現多個 promise 同步執行,不管有沒有拋出錯誤,都把結果收集起來?
forEach 后面能不能帶async函數?
首先我們來模擬一個異步函數:
const fetch = (forceTrue) => new Promise((resolve, reject) => {
if (Math.random() > 0.2 || forceTrue) {
resolve('success');
} else {
reject('error');
}
});
然后我們來試試使用 forEach 來執行多個async函數:
const result = [];
[0,1,2].forEach(async () => {
const value = await fetch(true);
result.push(value);
});
console.log(result); // 返回 []
可以看到,我們預期使用 await 獲取 fetch 的結果后存入 result 里面去,但是后面打印出來的卻是空數組。
我們使用 for 試一試:
const result = [];
for (let i = 0; i < 3; ++i) {
const value = await fetch(true);
result.push(value);
}
console.log(result); // 返回['success', 'success', 'success']
可以看到,使用 for 的時候按預期返回了。那么為什么用 forEach 就不行呢?我們看一看[mdn上面forEach的polyfill]源碼:
// Production steps of ECMA-262, Edition 5, 15.4.4.18
// Reference: http://es5.github.io/#x15.4.4.18
if (!Array.prototype.forEach) {
Array.prototype.forEach = function(callback, thisArg) {
var T, k;
if (this == null) {
throw new TypeError(' this is null or not defined');
}
// 1. Let O be the result of calling toObject() passing the
// |this| value as the argument.
var O = Object(this);
// 2. Let lenValue be the result of calling the Get() internal
// method of O with the argument "length".
// 3. Let len be toUint32(lenValue).
var len = O.length >>> 0;
// 4. If isCallable(callback) is false, throw a TypeError exception.
// See: http://es5.github.com/#x9.11
if (typeof callback !== "function") {
throw new TypeError(callback + ' is not a function');
}
// 5. If thisArg was supplied, let T be thisArg; else let
// T be undefined.
if (arguments.length > 1) {
T = thisArg;
}
// 6. Let k be 0
k = 0;
// 7. Repeat, while k < len
while (k < len) {
var kValue;
// a. Let Pk be ToString(k).
// This is implicit for LHS operands of the in operator
// b. Let kPresent be the result of calling the HasProperty
// internal method of O with argument Pk.
// This step can be combined with c
// c. If kPresent is true, then
if (k in O) {
// i. Let kValue be the result of calling the Get internal
// method of O with argument Pk.
kValue = O[k];
// ii. Call the Call internal method of callback with T as
// the this value and argument list containing kValue, k, and O.
callback.call(T, kValue, k, O);
}
// d. Increase k by 1.
k++;
}
// 8. return undefined
};
}
可以看到,里面是通過 while 循環里面多次調用callback.call(T, kValue, k, O);來實現的,由於它前面沒有 await,所以每次循環執行到這里的時候並沒有等待它執行完,最后打印 result 的時候就是空數組了。
map 和 reduce 后面能不能帶async函數?
我們再來看一看 map 和 reduce 的 demo:
// map
const mapResult = [0,1,2].map(async () => await fetch(true));
console.log(mapResult); // 返回 [Promise, Promise, Promise]
// reduce
const reduceResult = [0,1,2].reduce(async (accu) => {
const value = await fetch(true);
accu.push(value);
console.log('accu=====', typeof accu);
return accu;
}, []); // 報錯 Uncaught (in promise) TypeError: accu.push is not a function
console.log(reduceResult);
可以看到,兩個都沒有正常返回,我們先來看一看[mdn上面map的polyfill]源碼:
// Production steps of ECMA-262, Edition 5, 15.4.4.19
// Reference: http://es5.github.io/#x15.4.4.19
if (!Array.prototype.map) {
Array.prototype.map = function(callback/*, thisArg*/) {
var T, A, k;
if (this == null) {
throw new TypeError('this is null or not defined');
}
// 1. Let O be the result of calling ToObject passing the |this|
// value as the argument.
var O = Object(this);
// 2. Let lenValue be the result of calling the Get internal
// method of O with the argument "length".
// 3. Let len be ToUint32(lenValue).
var len = O.length >>> 0;
// 4. If IsCallable(callback) is false, throw a TypeError exception.
// See: http://es5.github.com/#x9.11
if (typeof callback !== 'function') {
throw new TypeError(callback + ' is not a function');
}
// 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
if (arguments.length > 1) {
T = arguments[1];
}
// 6. Let A be a new array created as if by the expression new Array(len)
// where Array is the standard built-in constructor with that name and
// len is the value of len.
A = new Array(len);
// 7. Let k be 0
k = 0;
// 8. Repeat, while k < len
while (k < len) {
var kValue, mappedValue;
// a. Let Pk be ToString(k).
// This is implicit for LHS operands of the in operator
// b. Let kPresent be the result of calling the HasProperty internal
// method of O with argument Pk.
// This step can be combined with c
// c. If kPresent is true, then
if (k in O) {
// i. Let kValue be the result of calling the Get internal
// method of O with argument Pk.
kValue = O[k];
// ii. Let mappedValue be the result of calling the Call internal
// method of callback with T as the this value and argument
// list containing kValue, k, and O.
mappedValue = callback.call(T, kValue, k, O);
// iii. Call the DefineOwnProperty internal method of A with arguments
// Pk, Property Descriptor
// { Value: mappedValue,
// Writable: true,
// Enumerable: true,
// Configurable: true },
// and false.
// In browsers that support Object.defineProperty, use the following:
// Object.defineProperty(A, k, {
// value: mappedValue,
// writable: true,
// enumerable: true,
// configurable: true
// });
// For best browser support, use the following:
A[k] = mappedValue;
}
// d. Increase k by 1.
k++;
}
// 9. return A
return A;
};
}
可以看到,源碼里面每次 while 循環把 callback 返回的結果賦值給 mappedValue,而 callback 在調用的時候也沒有使用 await,所以結果數組的每一個值都是一個 promise。
我們再看一看[mdn上面reduce的polyfill]源碼:
// Production steps of ECMA-262, Edition 5, 15.4.4.21
// Reference: http://es5.github.io/#x15.4.4.21
// https://tc39.github.io/ecma262/#sec-array.prototype.reduce
if (!Array.prototype.reduce) {
Object.defineProperty(Array.prototype, 'reduce', {
value: function(callback /*, initialValue*/) {
if (this === null) {
throw new TypeError( 'Array.prototype.reduce ' +
'called on null or undefined' );
}
if (typeof callback !== 'function') {
throw new TypeError( callback +
' is not a function');
}
// 1. Let O be ? ToObject(this value).
var o = Object(this);
// 2. Let len be ? ToLength(? Get(O, "length")).
var len = o.length >>> 0;
// Steps 3, 4, 5, 6, 7
var k = 0;
var value;
if (arguments.length >= 2) {
value = arguments[1];
} else {
while (k < len && !(k in o)) {
k++;
}
// 3. If len is 0 and initialValue is not present,
// throw a TypeError exception.
if (k >= len) {
throw new TypeError( 'Reduce of empty array ' +
'with no initial value' );
}
value = o[k++];
}
// 8. Repeat, while k < len
while (k < len) {
// a. Let Pk be ! ToString(k).
// b. Let kPresent be ? HasProperty(O, Pk).
// c. If kPresent is true, then
// i. Let kValue be ? Get(O, Pk).
// ii. Let accumulator be ? Call(
// callbackfn, undefined,
// « accumulator, kValue, k, O »).
if (k in o) {
value = callback(value, o[k], k, o);
}
// d. Increase k by 1.
k++;
}
// 9. Return accumulator.
return value;
}
});
}
可以看到,源碼里面每次循環的時候也是把 callback 的值賦給累計器 accu,而 callback 是一個 async 函數,所以這里 accu 其實是一個 promise 而不是數組,它沒有數組方法,所以報錯了。
