Skip to content

Instantly share code, notes, and snippets.

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

  • Save sj82516/5e04a4e29f31767a6a6bcbcc78b0fd55 to your computer and use it in GitHub Desktop.

Select an option

Save sj82516/5e04a4e29f31767a6a6bcbcc78b0fd55 to your computer and use it in GitHub Desktop.
// hello / world 依序執行
async function hello(){ await new Promise((res)=> setTimeout(()=>{console.log("hello"); res();}, 2000) ) }
async function world(){ await new Promise((res)=> setTimeout(()=>{console.log("world"); res();}, 2000) ) }
console.log("start")
await hello()
await world()
console.log("end")
// hello / world 同時執行
let helloTask = (async function hello(){ await new Promise((res)=> setTimeout(()=>{console.log("hello"); res();}, 2000) ) })()
let worldTask = (async function world(){ await new Promise((res)=> setTimeout(()=>{console.log("world"); res();}, 2000) ) })()
console.log("start")
await helloTask
await worldTask
console.log("end")
// 個人覺得比較好的並行寫法 (參考google文件教學)
async function hello(){ await new Promise((res)=> setTimeout(()=>{console.log("hello"); res();}, 2000) ) }
async function world(){ await new Promise((res)=> setTimeout(()=>{console.log("world"); res();}, 2000) ) }
console.log("start")
let helloTask = hello()
let worldTask = world()
await helloTask
await worldTask
console.log("end")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment