await async 串行,并行

1,257 阅读1分钟

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);
  }
}
复制代码