1. 程式人生 > >async, await 實驗筆記

async, await 實驗筆記

程式碼:

// 用 Promise 物件包裝非同步過程
//
function sleep(ms) {

  return new Promise((resolve) => {
    setTimeout(() => {
      resolve("sleep for " + ms + " ms")
    }, ms)
  })
}

// 定義非同步流程
//
async function asyncFun() {

  console.time('asy')

  const s1 = await sleep(2100)
  console.log('s1: ' + s1)

  const [s2, s3, s4] = await Promise.all([sleep(2000), sleep(1000), sleep(1500)])
  console.log(s2)
  console.log(s3)
  console.log(s4)

  const race = await Promise.race([sleep(2000), sleep(1000), sleep(800)])
  console.log('race: ' + race)

  console.timeEnd('asy')
  return 'ok'
}

asyncFun().then( data => {

  console.log(data)
}).catch( error => {
  console.log(error)
})

console.log('After all')

執行結果:

After all
s1: sleep for 2100 ms
sleep for 2000 ms
sleep for 1000 ms
sleep for 1500 ms
race: sleep for 800 ms
asy: 4907.754ms
ok

原文連結 https://www.jianshu.com/p/ffa5cbe9ab29