相关文章推荐
孤独的大海  ·  第十二届高交会报道之三:我校与多家企业签约- ...·  1 年前    · 
行走的冲锋衣  ·  细品旧金山深度10日游最佳路线推荐-旧金山1 ...·  1 年前    · 
讲道义的茴香  ·  能推荐一些很好看的小说吗? - 知乎·  1 年前    · 
豪情万千的芒果  ·  北五环外地铁重大突破!年底开通! ...·  2 年前    · 
老实的稀饭  ·  沙漠猫头鹰逃跑剧情 - 快看漫画·  2 年前    · 
Code  ›  JS循环中使用async、await的正确姿势开发者社区
test js代码 async promise
https://cloud.tencent.com/developer/article/2193343
文武双全的松树
2 年前
作者头像
科技新语
0 篇文章

JS循环中使用async、await的正确姿势

前往专栏
腾讯云
开发者社区
文档 意见反馈 控制台
首页
学习
活动
专区
工具
TVP
文章/答案/技术大牛
发布
首页
学习
活动
专区
工具
TVP
返回腾讯云官网
社区首页 > 专栏 > 用户9378866的专栏 > JS循环中使用async、await的正确姿势

JS循环中使用async、await的正确姿势

作者头像
科技新语
发布 于 2022-12-15 16:10:04
1.3K 0
发布 于 2022-12-15 16:10:04
举报

概览(循环方式 - 常用)

  • for
  • map
  • forEach
  • filter

声明遍历的数组和异步方法

声明一个数组:⬇️

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

再声明一个 promise 的异步代码: ⬇️

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

for 循环中使用

由于 for 循环并非函数,而 async 、 await 需要在函数中使用,因此需要在 for 循环外套一层 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() // 调用
for.gif

当使用 await 时,希望JavaScript暂停执行,直到等待 promise 返回处理结果。上述结果意味着 for 循环中有异步代码,是可以等到 for 循环中异步代码完全跑完之后再执行 for 循环后面的代码。 但是他不能处理回调的循环,如 forEach 、 map 、 filter 等,下面具体分析。

map 中使用

在 map 中使用 await , map 的返回值始是 promise 数组,这是因为异步函数总是返回 promise 。

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

结果:始终为 promise 数组

start
  Promise { <pending> },
  Promise { <pending> },
  Promise { <pending> },
  Promise { <pending> }

若果你想要等到 promise 的返回结果,可以使用 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()
// 结果
start
[ 'js', 'vue', 'node', 'react' ]

forEach 中使用

先上代码和结果

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

预期结果

'Start'
'vue'
'node'
'react'
'End'

实际结果 在 forEach 循环等待异步结果返回之前就执行了 console.log('end')

'Start'
'End'
'vue'
'node'
'react'

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

filter 中使用

使用 filter 过滤 item 为 vue 或者 react 的选项

正常使用 filter :

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

使用 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()

预期结果:

start
 
推荐文章
孤独的大海  ·  第十二届高交会报道之三:我校与多家企业签约-深圳大学
1 年前
行走的冲锋衣  ·  细品旧金山深度10日游最佳路线推荐-旧金山10日游攻略-旧金山行程【携程攻略】
1 年前
讲道义的茴香  ·  能推荐一些很好看的小说吗? - 知乎
1 年前
豪情万千的芒果  ·  北五环外地铁重大突破!年底开通! 大家最关心的13号线,时隔半年,终于有消息!(去年年底就说13号线拆分) 昨天,北京市规划和国土资源管理局对轨道交通地铁...
2 年前
老实的稀饭  ·  沙漠猫头鹰逃跑剧情 - 快看漫画
2 年前
今天看啥   ·   Py中国   ·   codingpro   ·   小百科   ·   link之家   ·   卧龙AI搜索
删除内容请联系邮箱 2879853325@qq.com
Code - 代码工具平台
© 2024 ~ 沪ICP备11025650号