for循环中使用async/await

async function printFiles () {
  const files = await getFilePaths();

  await Promise.all(files.map(async (file) => {
//耗时操作 const contents
= await fs.readFile(file, 'utf8') console.log(contents) })); }

 以上是并发操作,如果不想并发,使用for循环做:

async function dbFuc(db) {
  let docs = [{}, {}, {}];

  for (let doc of docs) {
    await db.post(doc);
  }
}

 

详见:https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop

   http://www.ruanyifeng.com/blog/2015/05/async.html

posted @ 2018-03-01 09:30  demonrain  阅读(28027)  评论(0编辑  收藏  举报