node-mysql實現異步操做(上)

實現 node-mysql 實現異步操做以前,先來談談JS中的異步操做。
在ES6中提供了Promise對象node


Promise對象的三種狀態

  • pending(進行中)
  • fulfilled(已成功)
  • rejected(已失敗)

狀態的轉換仍是單向不可逆的過程
pending -> fulfilled
pending -> rejectedmysql

基本使用

Promise 定義後,有 resolve 和 reject 兩個參數,分別對應 pending -> fulfilled狀態 和 pending -> rejected狀態es6

// 定義
const promise = new Promise(function(resolve, reject) {
  // 耗時較長的操做
  // 加載圖片,請求接口等

  if (/* 異步操做成功 */){
    resolve(value);
  } else {
    reject(error);
  }
});

執行時,不管執行 resolve 仍是 reject,返回的都是 Promise對象,要拿到 Promise對象 中的值,要在 then 中獲取。then 能夠有兩個函數,分別對應 Promise對象 中的 resolve參數 和 reject參數sql

// 使用
promise.then(function(resolve){
    ...
},function(reject){
    ...
})

模擬異步操做的例子

const timeout = (ms) => {
    return new Promise((resolve, reject) => {
        resolve('done job')
    });
}

console.log(timeout(100)) // Promise { 'done job' }

timeout(100).then(res => {
    console.log(res) // done job
})

仔細想一想,promise對象 中的數據從 then 中才能拿到數據,可是 then 這種鏈式調用仍是可能形成回調地獄,若是能夠像同步函數同樣操做,讓 timeout(100) 直接有返回值,那就更好了。
ES2017 標準引入了 async 函數,在 async 函數中 promise對象 前用 await 就能夠直接從 promise對象 中直接拿到數據了。promise

對上面的例子進行修改

在 async函數 中打印的值和在 then 中打印的如出一轍異步

const timeout = (ms) => {
    return new Promise((resolve, reject) => {
        resolve('done job')
    });
}

console.log(timeout(100)) // Promise { 'done job' }

timeout(100).then(res => {
    console.log(res) // done job
})

const getStr = async () => {
    const str = await timeout(100);
    console.log(str) // done job
}

getStr()
相關文章
相關標籤/搜索