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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM