promise 和 async 的用法

promise

// 先構造一個 promise 函數
// resolve 和 reject 都是一個函數
// resolve 在成功時調用
// reject 在失敗時調用
function promise() {
  return new Promise((resolve, reject) => {
    let tar = Math.random(0, 1)
    if (tar > 0.5) {
      console.log('suceess')
      setTimeout(function() {
        resolve('resolve')  
      }, 1000)
    } else {
      console.log('fail')
      setTimeout(function() {
        reject('reject')
      }, 1000)
    }
  })
}

// then 和 catch 第一個參數爲resolve狀態時的回調,第二個參數爲reject狀態時的回調
// catch 相當於 then(null, reject)
promise().then(
  (resolve) => console.log('then', resolve)
).catch(
  (reject) => console.log('catch', reject)
)


// then 後面還可以接 then 一直鏈式調用
// 第一個 then 接受的參數是 resolve 函數傳過來的參數
// 第二個 then 接受一個參數是第一個 then 返回的值
promise().then(
  (resolve) => (resolve + 1)  // 接受 resolve 返回 resolve + 1
).then(
  (plusOne) => console.log(plusOne)  // 接受 resolve +1 並打印
).catch(
  (reject) => console.log('catch', reject)
)

async

// 同樣需要一個 promise 對象
function promise() {
  return new Promise((resolve, reject) => {
    let tar = Math.random(0, 1)
    if (tar > 0.5) {
      console.log('success')
      setTimeout(function() {
        resolve('resolve')
      }, 1000)
    } else {
      console.log('fail')
      setTimeout(function() {
        reject('reject')
      }, 1000)
    }
  })
}

// 只是調用的方法跟 then/catch 不一樣
// async 函數執行時,一旦遇到 await 就會先返回,等異步操作完成,再接着執行後面的操作
async function async() {
  const res = await promise()
  console.log(res)
  console.log('wait')
  return res
}

// async 函數返回 promise 對象
// 只有函數內的 await 語句全部執行完,或者遇到 return 或 拋出錯誤,纔會發生狀態改變
// 如果發生錯誤或狀態爲 reject 則執行 catch
async().then(
  (res) => console.log(res)
).catch(
  (e) => console.log(e)
)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章