2015年12月21日 星期一

Javascript - ES7 包著糖衣的 async

webber0928

ES7 的新功能 -  async ... awite

但是在做 foreach 的時候卻碰到問題,我的觀念是 async 幫我做到平行處理的機制,

但是加上 foreach 後完全不是這麼回事...

詢問一下古哥,他幫我找到了這篇 Taming the asynchronous beast with ES7

他一樣有碰到 Loop 的問題

However, if you try to use an async function, then you will get a more subtle bug:
let docs = [{}, {}, {}];

// WARNING: this won't work
docs.forEach(async function (doc, i) {
  await db.post(doc);
  console.log(i);
});
console.log('main loop done');
This will compile, but the problem is that this will print out:
main loop done
0
1
2
解法如下:
let  docs  =  [{},  {},  {}]; 
let  promises  =  docs . map (( doc )  =>  db . post ( doc )); 

let  results  =  []; 
for  ( let  promise  of  promises )  { 
  results . push ( await  promise ); 
} 
console . log ( results );

筆記...


By webber0928

一個小菜鳥工程師,對籃球還有夢想的男孩。

0 意見:

張貼留言

Coprights @ 2016, Blogger Templates Designed By Templateism | Distributed By Gooyaabi Templates