es6的promise對象解決了js異步回調函數多重嵌套的的噩夢,不再用寫像這樣的代碼node
query('select * from user',function(err,data) { query('select * from user1',function(err,data) { query('select * from user2',function(err,data) { //無窮無盡的異步操做。。。 }) }) })
而能夠像這樣。es6
query('select * from user') .then(function(data) { return query('select * from user1') }) .then(function(data) { return query('select * from user2') }) .then(function(data) { //後續操做。。。 })
代碼的可讀性獲得了大大的提高,而且更容易維護。可是promise並非萬能的,好比說在循環中有多個異步操做,有無窮多個then函數就比較麻煩了,好比這樣promise
//查詢訂單及每一個訂單的每一個商品 query('select * from order') .then(data => { var orders = data for(let order of orders) { query('select * from order_prod where oid='+order.oid) .then(data => { order.prods = data }) } //最終須要獲得結果 console.log(orders) })
這裏須要獲得最終的結果就比較使人頭疼了,好在es7的async/await異步方案爲咱們提供瞭解決方案。node.js7.6已經原生支持async/await,因此把node更新到7.6以上,就能夠放心使用啦。async 能夠聲明一個異步函數,此函數須要返回一個 Promise 對象。await 能夠等待一個 Promise 對象 resolve,並拿到結果。好比這樣異步
async function sleep(timeout) { return new Promise((resolve, reject) => { setTimeout(function() { resolve(); }, timeout); }); } (async function() { console.log('Do some thing, ' + new Date()); await sleep(3000); console.log('Do other things, ' + new Date()); })(); //Do some thing, Mon Feb 23 2015 21:52:11 GMT+0800 (CST) //Do other things, Mon Feb 23 2015 21:52:14 GMT+0800 (CST)
因此在循環promise取得最終結果就能夠是這樣 async
let getOrderProd = async data => { var order = data for(let order of orders) { //將以前封裝的基於promised的query函數還原成普通的異步回調模式 await f(order) } //最終須要獲得結果 console.log(orders) return new Promise((reslove,reject) => { reslove(orders) }) } function f(i) { return new Promise((resolve,reject) => { query1('select * from order_prod where oid='+order.oid, function(err,data){ i.prods = data resolve(i) }) }) } query('select * from order') .then(getOrderProd).then(data => { //後續操做。。。。。 })
這樣循環異步操做的問題就解決了。函數