それは質問に来たときに最近ノードとの静的なファイルサーバを書いて、コールの問題は、内部のforeachループで/非同期非同期機能を待っています。この問題は、数回に遭遇し、ここで忘れないようにする次の時間を書き留めます。
問題を再現するために、
var getNumbers = () => {
return Promise.resolve([1, 2, 3])
}
var multi = num => {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (num) {
resolve(num * num)
} else {
reject(new Error('num not specified'))
}
}, 1000)
})
}
async function test () {
var nums = await getNumbers()
nums.forEach(async x => {
var res = await multi(x)
console.log(res)
})
}
test()
私の所望の結果を実行するためのテスト機能は、コードが直列に実行された後、私はだろう第二等それぞれに出力数... 1 ... 4 ... 9が、得られた結果は、今しているのを待ちます第二と出力149
問題を発見
なぜループのために/ために...その実現可能に/非同期機能を待つが、それは内部のforEachにできないのですか?まず、ポリフィルMDNのウェブサイトを見てください
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');
}
var O = Object(this);
var len = O.length >>> 0;
if (typeof callback !== "function") {
throw new TypeError(callback + ' is not a function');
}
if (arguments.length > 1) {
T = thisArg;
}
k = 0;
while (k < len) {
var kValue;
if (k in O) {
kValue = O[k];
callback.call(T, kValue, k, O);
}
k++;
}
};
}
我々は、コールバック関数内に記述のforEachを見ることができる内部を循環しながら、簡略化の下で、直接呼び出されるとき
Array.prototype.forEach = function (callback) {
// this represents our array
for (let index = 0; index < this.length; index++) {
// We call the callback for each entry
callback(this[index], index, this)
}
}
非同期ループを実行するための機能で等価
async function test () {
var nums = await getNumbers()
// nums.forEach(async x => {
// var res = await multi(x)
// console.log(res)
// })
for(let index = 0; index < nums.length; index++) {
(async x => {
var res = await multi(x)
console.log(res)
})(nums[index])
}
}
ソリューション
...のforEachの、またはループのための場所での使用のために
async function test () {
var nums = await getNumbers()
for(let x of nums) {
var res = await multi(x)
console.log(res)
}
}