async与await

function test () {
  return new Promise(resolve => {
    setTimeout(() => {
      console.log('test')
      resolve()
    }, 1000)
  })
}
function test1 () {
  return new Promise(resolve => {
    setTimeout(() => {
      console.log('test1')
      resolve()
    }, 1000)
  })
}
function test2 () {
  return new Promise(resolve => {
    setTimeout(() => {
      console.log('test2')
      resolve()
    }, 1000)
  })
}
async function call () {
  await test()
  await test1()
  await test2()
}
call ()

[外链图片转存失败(img-KGTBmPON-1566149826679)(https://upload-images.jianshu.io/upload_images/11158618-fafb1531faa895a1.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)]

继发执行

function call () {
  Promise.all([test(), test1(), test2()])
}
call()

[外链图片转存失败(img-iadkwTxC-1566149826681)(https://upload-images.jianshu.io/upload_images/11158618-a881ff99cdbd8005.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)]

function getUserInfo (id) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve({
        id: id,
        name: 'xxx',
        age: 'xxx'
      })
    }, 200)
  })
}
const users = [{id: 1}, {id: 2}, {id: 3}]
let userInfos = []
users.forEach(async user => {
  let info = await getUserInfo(user.id)
  userInfos.push(info)
})
console.log(userInfos) // []

function getUserInfo (id) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve({
        id: id,
        name: 'xxx',
        age: 'xxx'
      })
    }, 200)
  })
}
const users = [{id: 1}, {id: 2}, {id: 3}]
let userInfos = []
async function call() {
  for (user of users) {
    let info = await getUserInfo(user.id)
    userInfos.push(info)
  }
  console.log(userInfos)
}
call()

继发式的

function getUserInfo (id) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve({
        id: id,
        name: 'xxx',
        age: 'xxx'
      })
    }, 200)
  })
}
const users = [{id: 1}, {id: 2}, {id: 3}]
let userInfos = []
const promises = users.map(user => getUserInfo(user.id))
Promise.all(promises).then(res => {
  userInfos = res
  console.log(userInfos)
})


若本号内容有做得不到位的地方(比如:涉及版权或其他问题),请及时联系我们进行整改即可,会在第一时间进行处理。


请点赞!因为你们的赞同/鼓励是我写作的最大动力!

欢迎关注达叔小生的简书!

这是一个有质量,有态度的博客

[外链图片转存失败(img-2s2GP3mM-1566149826682)(https://upload-images.jianshu.io/upload_images/11158618-9ab0d3fef85d80ce?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)]

posted @ 2019-08-19 01:37  达达前端  阅读(140)  评论(0编辑  收藏  举报