nodejs 中同步异步多种写法

栏目: Node.js · 发布时间: 6年前

内容简介:nodejs 的同步异步写起来真爽,特别是结合 typescript,简直上天!感觉可以取代 go 的异步呢,哈哈。传统 for 循环:进阶 forEach:

nodejs 的同步异步写起来真爽,特别是结合 typescript,简直上天!感觉可以取代 go 的异步呢,哈哈。

同步循环

传统 for 循环:

for (let i = 0; i < array.length; i++) {
  const item = array[i]
  // do something
}

进阶 forEach:

array.forEach(item => {
  //do something
})

异步循环

全部异步,不关心结果

async function doArray(array) {
  array.forEach(async(item) => {
    await doItem(item)
  })
  console.log('loop done! But each item is sitll doing')
}

依次同步

async function doArray(array) {
  for (const item of array) {
    await doItem(item)
  }
  console.log('every item done!')
}

异步执行,同步等结果

async function doArray(array) {
  const promises = array.map(item => doItem(item))
  await Promise.all(promises)
  console.log('every item done!')
}

以上所述就是小编给大家介绍的《nodejs 中同步异步多种写法》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Computer Age Statistical Inference

Computer Age Statistical Inference

Bradley Efron、Trevor Hastie / Cambridge University Press / 2016-7-21 / USD 74.99

The twenty-first century has seen a breathtaking expansion of statistical methodology, both in scope and in influence. 'Big data', 'data science', and 'machine learning' have become familiar terms in ......一起来看看 《Computer Age Statistical Inference》 这本书的介绍吧!

SHA 加密
SHA 加密

SHA 加密工具

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

html转js在线工具
html转js在线工具

html转js在线工具