1. 程式人生 > 其它 >JavaScript執行機制(四)promise與async函式

JavaScript執行機制(四)promise與async函式

promise和async函式

promise
  let p = new Promise((resolve)=>{
    resolve("hello world")
  })

  p.then((data) => {
    console.log(data) // hello world
  })
async函式
// async函式的返回值是promise物件
  async function fun(){
    return 1
  }
  let a = fun()
  console.log(a) // Promise { 1 }
  fun().then((data)=>{
    console.log(data) // 1
  })

await
  let p1 = new Promise((resolve) => {
    resolve(1)
  })

  let p2 = new Promise((resolve) => {
    resolve(2)
  })

  async function fun(){
    let a = await p1
    let b = await p2
    console.log(a) // 1
    console.log(b) // 2
  }

  fun()
  async function fun1(){
    let data = await fun2()
    console.log(data) // 相當於then中的程式碼
  }
  async function fun2(){
    console.log(data) // 同步
    return 100
  }
  fun1()
  // 執行順序是 200 100 
例子-執行順序
  console.log(1)
  async function async1(){
    await async2()
    console.log(2)
  }
  async function async2(){
    console.log(3)
  }
  async1()
  setTimeout(function () {
    console.log(4)
  },0)
  new Promise((resolve)=>{
    console.log(5)
    resolve()
  }).then(()=>{
    console.log(6)
  }).then(()=>{
    console.log(7)
  })
  console.log(8)
  // 1358267
  1. 同步
  2. process.nextTick
  3. 微任務(promise.then)
  4. 巨集任務(計時器,ajax,讀取檔案)
  5. setImmediate