關於異步的問題

兩個異步方法並行,等兩個都執行結束

方法一, 用Promise.all

let wake = (time) => {
  let now = new Date().getSeconds()
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(`當前時間 ${now}, 以後時間 ${new Date().getSeconds()}, ${time / 1000}秒後醒來`)
    }, time)
  })
}

let p1 = wake(3000)
let p2 = wake(2000)

Promise.all([p1, p2]).then((result) => {
  console.log(result) // [ '3秒後醒來', '2秒後醒來' ]
  console.log('--------', new Date().getSeconds())
}).catch((error) => {
  console.log(error)
})

結果:
[ '當前時間 39, 以後時間 42, 3秒後醒來', '當前時間 39, 以後時間 41, 2秒後醒來']
-------- 42
拓展:
Promise.race用法相似用Promise.all,區別於Promise.all裏面的方法是同時執行且等到全部異步方法執行完了纔會回調;Promise.race則是裏面方法先執行結束,就返回那個結果,且無論結果自己是成功狀態仍是失敗狀態異步

參考:https://www.jianshu.com/p/7e6...async

方法二,用async庫(不是es7的 async/await)

並行 async.parallel方法能夠解決
拓展:async的其餘方法
串行 無關聯 async.series
串行 有關聯 async.waterfallcode

自動 async.autoget

for循環裏面執行異步方法,確保循環異步的同時獲取循環以後的結果

方法一 異步for循環 async.forEach

let arr = [1000, 2000, 3000]
let newArr = []

async.forEach(arr, (value, done) => {
  let now = new Date().getSeconds()
  setTimeout(function () {
    newArr.push(value)
    console.log('當前時間:', now, '結束時間:', new Date().getSeconds())
    done()
  }, value)
  // timeOut(value)
}, err => {
  if (err) console.error(err.message)
  console.log(newArr)
  console.log('最終時間', new Date().getSeconds())
})
console.log('最終時間2', new Date().getSeconds())

結果:
最終時間2 18
當前時間: 18 結束時間: 19
當前時間: 18 結束時間: 20
當前時間: 18 結束時間: 21
[ 1000, 2000, 3000 ]
最終時間 21it

相關文章
相關標籤/搜索