Skip to content

Instantly share code, notes, and snippets.

@sj82516
Last active June 25, 2018 21:13
Show Gist options
  • Select an option

  • Save sj82516/9733d8b406fdbde14508d57da1d42988 to your computer and use it in GitHub Desktop.

Select an option

Save sj82516/9733d8b406fdbde14508d57da1d42988 to your computer and use it in GitHub Desktop.
// 代表非同步操作
let timePromise = (time)=>{return new Promise(res => setTimeout(()=> res(), time))}
let taskA = timePromise(1000)
await taskA
console.log("TaskA done")
// 此處B,C會並行
let taskB = timePromise(2000)
let taskC = timePromise(500)
await taskB
await taskC
console.log("TaskB done")
console.log("TaskC done")
// 此處 TaskD要等到 TaskB也完成才能開始
console.log("TaskD done")
console.log("TaskE done")
console.log("TaskF done")
/* 用async iife 封裝任務相依性 */
let timePromise = (time)=>{return new Promise(res => setTimeout(()=> res(), time))}
let taskA = (async ()=> { await timePromise(1000); console.log("TaskA done")})()
await taskA
let taskB = (async ()=> { await timePromise(2000); console.log("TaskB done")})()
let taskC = (async ()=> { await timePromise(500); console.log("TaskC done")})()
let taskD = (async ()=> { await taskC; console.log("TaskD done")})()
let taskE = (async ()=> { await taskB; await taskC; console.log("TaskE done")})()
let taskF = (async ()=> { await taskD; await taskE; console.log("TaskF done")})()
await taskF;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment