美文网首页
async await 与 forEach()一起用坏的味道

async await 与 forEach()一起用坏的味道

作者: bypwan | 来源:发表于2022-10-28 10:57 被阅读0次

    趟过的一个坑:Array.forEach与 async await一起使用,并没有达到自己预期的效果,后面查询资料得知:forEach的第一个参数回调函数并没有对promise对象做任何处理,导致结果出现异常,我们可以用for ..of 或者for循环代替
    如下代码

    async function test(){
      let readFileFun = [readFileA(),readFileB(),readFileC()] // 数组里的3个方法都是返回Promise的 
        //异步请求
       for(let i = 0; i< readFileFun.length;i++){
        let re = await readFileFun[i]
        console.log(re)
        console.log('end',i+1)
       }
    }
    

    需求:
    数组循环中获取异步请求,异步请求全部执行完成后做下一个操作,解决方法:
    异步请求全部执行完后做接下来的工作,可以通过
    await Promise.all()
    伪代码如下:

    async function printFiles(){
    const files = await getFilePaths() // 异步请求获取文件数组
    //通过aysnc await结合map进行循环 【有序的执行异步】
     await Promise.all(files.map(async(file) => {
          const contents = await fs.readFile('file','utf8') //异步读取文件
          console.log(contents)
     })
    )
    //所以的循环完成进行下一步的操作
    }
    

    相关文章

      网友评论

          本文标题:async await 与 forEach()一起用坏的味道

          本文链接:https://www.haomeiwen.com/subject/llnxtdtx.html