溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

JS循環(huán)中正確使用async、await的方法是什么

發(fā)布時(shí)間:2021-12-18 13:16:05 來(lái)源:億速云 閱讀:184 作者:柒染 欄目:開(kāi)發(fā)技術(shù)

JS循環(huán)中正確使用async、await的方法是什么,針對(duì)這個(gè)問(wèn)題,這篇文章詳細(xì)介紹了相對(duì)應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問(wèn)題的小伙伴找到更簡(jiǎn)單易行的方法。

概覽(循環(huán)方式 - 常用)

  • for

  • map

  • forEach

  • filter

聲明遍歷的數(shù)組和異步方法

聲明一個(gè)數(shù)組:??

const skills = ['js', 'vue', 'node', 'react']

再聲明一個(gè)promise的異步代碼: ??

function getSkillPromise (value) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(value)
    }, 1000)
  })
}

for 循環(huán)中使用

由于for循環(huán)并非函數(shù),而async、await需要在函數(shù)中使用,因此需要在for循環(huán)外套一層function

async function test () {
  for (let i = 0; i < skills.length; i++) {
    const skill = skills[i]
    const res = await getSkillPromise(skill)
    console.log(res)
  }
}

test() // 調(diào)用

JS循環(huán)中正確使用async、await的方法是什么

當(dāng)使用await時(shí),希望JavaScript暫停執(zhí)行,直到等待 promise 返回處理結(jié)果。上述結(jié)果意味著for循環(huán)中有異步代碼,是可以等到for循環(huán)中異步代碼完全跑完之后再執(zhí)行for循環(huán)后面的代碼。

但是他不能處理回調(diào)的循環(huán),如forEach、map、filter等,下面具體分析。

map 中使用

在map中使用await, map 的返回值始是promise數(shù)組,這是因?yàn)楫惒胶瘮?shù)總是返回promise。

async function test () {
  console.log('start')
  const res = skills.map(async item => {
    return await getSkillPromise(item)
  })
  console.log(res)
  console.log('end')
}

test()

結(jié)果:始終為promise數(shù)組

start
[
  Promise { <pending> },
  Promise { <pending> },
  Promise { <pending> },
  Promise { <pending> }
]
end

若果你想要等到promise的返回結(jié)果,可以使用promise.all()處理一下

async function test () {
  console.log('start')
  const res = skills.map(async item => {
    return await getSkillPromise(item)
  })
  const resPromise = await Promise.all(res)
  console.log(resPromise)
  console.log('end')
}

test()

// 結(jié)果
start
[ 'js', 'vue', 'node', 'react' ]
end

forEach 中使用

先上代碼和結(jié)果

async function test () {
  console.log('start')
  skills.forEach(async item => {
    const res = await getSkillPromise(item)
    console.log(res)
  })
  console.log('end')
}

test()

預(yù)期結(jié)果

'Start'

'js'

'vue'

'node'

'react'

'End'

實(shí)際結(jié)果 在forEach循環(huán)等待異步結(jié)果返回之前就執(zhí)行了console.log('end')

'Start'

'End'

'js'

'vue'

'node'

'react'

JavaScript 中的 forEach不支持 promise 感知,也支持 async 和await,所以不能在 forEach 使用 await 。

filter 中使用

使用filter過(guò)濾item為vue或者react的選項(xiàng)

正常使用 filter:

async function test () {
  console.log('start')
  const res = skills.filter(item => {
    return ['vue', 'react'].includes(item)
  })
  console.log(res)
  console.log('end')
}

test() // 調(diào)用

// 結(jié)果
start
[ 'vue', 'react' ]
end

使用 await后:

async function test () {
  console.log('start')
  const res = skills.filter(async item => {
    const skill = await getSkillPromise(item)
    return ['vue', 'react'].includes(item)
  })
  console.log(res)
  console.log('end')
}

test()

預(yù)期結(jié)果:

start

[ 'vue', 'react' ]

end

實(shí)際結(jié)果:

[ 'js', 'vue', 'node', 'react' ]

end

結(jié)論:因?yàn)楫惒胶瘮?shù)getSkillPromise返回結(jié)果返回的promise總是真的,所以所有選項(xiàng)都通過(guò)了過(guò)濾

  1. 如果你想連續(xù)執(zhí)行await調(diào)用,請(qǐng)使用for循環(huán)(或任何沒(méi)有回調(diào)的循環(huán))。

  2. 永遠(yuǎn)不要和forEach一起使用await,而是使用for循環(huán)(或任何沒(méi)有回調(diào)的循環(huán))。

  3. 不要在 filter 和 reduce 中使用 await,如果需要,先用 map 進(jìn)一步驟處理,然后在使用 filter 和 reduce 進(jìn)行處理。

關(guān)于JS循環(huán)中正確使用async、await的方法是什么問(wèn)題的解答就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,如果你還有很多疑惑沒(méi)有解開(kāi),可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識(shí)。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI