实现 node-mysql 实现异步操做以前,先来谈谈JS中的异步操做。
在ES6中提供了Promise对象node
状态的转换仍是单向不可逆的过程
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()