【问题标题】:Why await is not working in Async series? How can i implement it?为什么 await 在异步系列中不起作用?我该如何实施?
【发布时间】:2021-10-21 23:41:40
【问题描述】:

请检查下面的示例代码,async eachseries 中的 await 不工作,为什么?如何解决这个问题?

async.eachSeries(myaccomplishmentinfo, (imgitem, next) => {
            let imgfilename = req.body.userid + '_' + uniqid.time() + '_' + imgitem.order;
            let img1_buff = Buffer.from(imgitem.filecontent, 'base64');
            let data = {};
            data.binaryData = img1_buff;
            data.folderName = 'myaccomplishments';
            data.fileName = imgfilename;
            data.filetype = imgitem.filetype;
            await s3Lib.storeData(data, (res) => {
                myaccomplishmentimgdetail.push({
                    uniqueid: random,
                    filename: imgfilename,
                    filetype: imgitem.filetype,
                    imagetag: imgitem.imagetag,
                    imgorder: imgitem.order,
                    created_at: getdbdate,
                    modified_at: getdbdate
                });
                console.log(res)
                next();
            }) 

【问题讨论】:

  • 错误是什么
  • “不工作”是什么意思?什么是“问题”?

标签: node.js angularjs


【解决方案1】:

这里的问题是你需要将async添加到eachSeries函数中。

另外,不要使用您已经在等待结束的 next 参数,如下所示:

async.eachSeries(myaccomplishmentinfo, async (imgitem) => {
            let imgfilename = req.body.userid + '_' + uniqid.time() + '_' + imgitem.order;
            let img1_buff = Buffer.from(imgitem.filecontent, 'base64');
            let data = {};
            data.binaryData = img1_buff;
            data.folderName = 'myaccomplishments';
            data.fileName = imgfilename;
            data.filetype = imgitem.filetype;
            await s3Lib.storeData(data, (res) => {
                myaccomplishmentimgdetail.push({
                    uniqueid: random,
                    filename: imgfilename,
                    filetype: imgitem.filetype,
                    imagetag: imgitem.imagetag,
                    imgorder: imgitem.order,
                    created_at: getdbdate,
                    modified_at: getdbdate
                });
                console.log(res)
            }) 

【讨论】:

    【解决方案2】:

    我觉得应该是这样的:

    async.eachSeries(myaccomplishmentinfo, async (imgitem, next) => {
               // do stuff ...
    } 
    

    注意回调函数现在是异步的。

    Raz 的回答看起来也不错

    【讨论】:

      猜你喜欢
      • 2020-10-04
      • 2021-01-12
      • 1970-01-01
      • 2017-12-05
      • 2017-10-26
      • 1970-01-01
      • 2020-03-09
      • 2017-05-02
      相关资源
      最近更新 更多