我们会碰到这种情形:
const result = [];
const ids = [1, 2, 3, 4, 5];
ids.forEach(id => {
const list = http(id); //http为一个异步请求,拿到对应id的信息
result.push(list.name);
})
console.log(result); // []
结果事与愿违是一个空的数组,其实我们希望的结果打印对应id
的信息name
;原因在于http
是一个异步请求,那么forEach
的函数回调则会把异步请求放入事件队列里,然后执行console.log(result)
,最后将事件队列里的函数放入主线程执行,所以我们看到打印的结果是一个空数组,如果我们在console.log(result)
后面加上这么一段代码setTimeout(() => {console.log(result)})
,那么其打印的结果就是我们所要得到的信息名称;所以我们想着能不能不通过这种setTimeout
去拿到我们想要的结果,而是通过在异步请求前加入await
来实现我们要的结果:
const result = [];
const ids = [1, 2, 3, 4, 5];
ids.forEach(async (id) => {
const list = await http(id); //http为一个异步请求,拿到对应id的信息
result.push(list.name);
})
console.log(result); // []
结果出乎意料,依然打印的是一个空的数组,所以我们这时候就需要来看看forEach
方法是怎么封装的了,这是forEach
方法的一段源码:
// 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) {