【问题标题】:Looping through array of objects and performing async functions遍历对象数组并执行异步函数
【发布时间】:2022-11-29 17:49:12
【问题描述】:

我正在使用 NextJS,我的状态下有一组资产(图像)。我需要将这些图像发布到 API。我有一个使用以下语法执行此操作的对象:

let response = await api_image.post()
if(response.status !== 201) {
    resolve()
}

因此,对于资产数组中的每个图像,我需要先创建一个新的api_image,然后将其发布。我对承诺很陌生,到目前为止,从 StackOverflow 研究来看,我将以下代码放在一起:

 async postAssetsToAPI(asset) {
        let registrationID = this.registrationID
        return new Promise(async(resolve, reject) => {
            let api_image = new api_image()
            api_image.filename = asset.filename
            api_image.uploadOwnerType = 'registration'
            api_image.uploadOwnerID = registrationID
            let response = await api_image.post()
            if(response.status !== 201) {
                resolve()
            }
        })
    }

    async redirectToFinish() {

        let registrationID = this.registrationID
        let success = true
    
        console.log('redirectToUploadMetadata')

        const promises = this.props.assets.map(this.postAssetsToAPI)
        await Promise.all(promises).then(
            () => {console.log('promises succeeded')},
            () => {console.log('promises failed')}
        )

    }

这只是失败并显示控制台消息promises failed。另外,我不确定 new Promise(async(resolve, reject) 里面的 async,感觉就像我只是在任何地方使用异步来让它工作,但如果没有它我就无法在承诺中等待。

实现这一目标的最佳方法是什么?我需要每个 api_image 来在数据库中发布和保存数据,并在完成后在最后显示一条消息。

【问题讨论】:

  • 你已经有一个异步功能,所以你不需要new Promise...

标签: javascript reactjs next.js promise es6-promise


【解决方案1】:

不要将 asyncnew Promisethen 混合搭配 – 您只需要

async function redirectToFinish() {
  const registrationID = this.registrationID;

  const uploadPromises = this.props.assets.map(async (asset) => {
    const api_image = new api_image();
    api_image.filename = asset.filename;
    api_image.uploadOwnerType = "registration";
    api_image.uploadOwnerID = registrationID;
    const response = await api_image.post();
    if (response.status !== 201) {
      throw new Error("Error uploading image");
    }
  });

  try {
    await Promise.all(uploadPromises);
  } catch (err) {
    console.log(err);
    return;
  }
  console.log("redirectToFinish");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-19
    相关资源
    最近更新 更多