# 当 forEach 遇上了 async 与 await

## 前言

``````// id 数组
const arr = [1, 2, 3, ...]
const infoList = new Array(arr.length)
arr.forEach((id, index) => {
const sql = `select name from users where id='\${id}';`
const res = exec(sql) // 这里有问题
infoList[index].id = id
infoList[index].name = res
})

``````const arr = [1, 2, 3, ...]
arr.forEach(async (id, index) => {
const sql = `select name from users where id='\${id}';`
const res = await exec(sql)
infoList[index].id = id
infoList[index].name = res
})

## forEach

``````Array.prototype.myForEach = function(callback, thisArg) {
for (let i = 0; i < this.length; i ++) {
callback.call(thisArg, this[i], i, this)
}
}

``````const arr = [1, 2, 3]

arr.myForEach((item, index, array) => {
console.log(item, index)
})

``````// id 数组
const arr = [1, 2, 3, ...]
arr.myForEach(async (id, index) => {
const sql = `select name from users where id='\${id}';`
const res = await exec(sql)
infoList[index].id = id
infoList[index].name = res
})

## 解决

``````Array.prototype.myForEach = async function(callback, thisArg) {
for (let i = 0; i < this.length; i ++) {
await callback.call(thisArg, this[i], i, this)
}
}
{"ft_lang_label":"__label__zh","ft_lang_prob":0.76394254,"math_prob":0.98994637,"size":2010,"snap":"2021-43-2021-49","text_gpt3_token_len":1033,"char_repetition_ratio":0.13609172,"word_repetition_ratio":0.38549617,"special_character_ratio":0.2835821,"punctuation_ratio":0.2146739,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9906822,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2021-12-01T22:37:39Z\",\"WARC-Record-ID\":\"<urn:uuid:eb80f222-a1a0-42f9-9f53-2708d6866201>\",\"Content-Length\":\"86373\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:ead63ca9-4550-4fc7-ba0c-b8ab318d8ab6>\",\"WARC-Concurrent-To\":\"<urn:uuid:92be3f02-d4be-4977-8a3f-db6779d589e2>\",\"WARC-IP-Address\":\"47.246.24.231\",\"WARC-Target-URI\":\"https://juejin.cn/post/6913350888845213703\",\"WARC-Payload-Digest\":\"sha1:UTMGURQPSF2AW6KCUF4RF6OVJ3QNP3K3\",\"WARC-Block-Digest\":\"sha1:5IDFLBCNWQ4UEQSU52G2DDG2OTFDTEEI\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2021/CC-MAIN-2021-49/CC-MAIN-2021-49_segments_1637964360951.9_warc_CC-MAIN-20211201203843-20211201233843-00156.warc.gz\"}"}