【问题标题】:Promise.all() for a promiseArray not returning any valuesPromise.all() 用于 promiseArray 不返回任何值
【发布时间】:2020-08-27 17:33:56
【问题描述】:

我有以下设置,我试图调用一个返回Promise 的函数,而该函数又具有Promise.all() 调用以进行无限数量的axios.post() 调用。我尝试使用axios.all()axios.spread(...responses),但没有运气。我还尝试了一些经验丰富的用户发布到 SO 的示例。但仍然没有运气。

值得注意的是调用,只是返回的响应是未定义的。

被调用的函数如下:

createSurveyResult(surveyResults) {
  let token = Vue.prototype.$auth.getLocalStorage(`${this.activeUser.uuid)_{process.env.NODE_ENV}_ACCESS_TOKEN`)

  if (token) {
    axiosModified.defaults.headers.common['Authorization'] = `Bearer ${token}`
  }

  return new Promise(resolve => {
    let promiseArray = surveyResults.map(payload => {
      axiosModified.post('/feedback/results/', payload)
    })

    Promise.all(promiseArray).then(responses => {
      responses.forEach(res => console.log(res))
      console.log('submitted all axios calls');
      resolve(responses)
    }).catch(error => {
      resolve(error.response)
    })
  })
}

被称为:

this.$surveys.createSurveyResult(surveyResults).then((responses) => {
  console.log(responses)
});

然而,Promise.all() 中的两个 console.log(res) res 对象返回都未定义,正在调用 console.log('submitted all axios calls');,并且 then() 回调的响应返回为:

我想知道我在这里做错了什么?

【问题讨论】:

  • 因为surveyResults.map()方法中的回调没有返回任何东西
  • @GuyIncognito 完美,谢谢 - 这实际上是在返回映射调用中删除 {} 的情况。哦!
  • 或在axiosModified.post之前添加return
  • 仅供参考,将Promise.all() 包装在new Promise() 中是一种反模式。如果您已经有一个承诺(即Promise.all() 创建的那个),则不需要创建另一个承诺。只需返回 Promise.all() 并使用 return responses 而不是 resolve(responses)stackoverflow.com/questions/23803743/…
  • 啊,是的,完全正确。认为我只是在代码上混淆代码,而不是在这里真正思考。谢谢!

标签: javascript promise axios


【解决方案1】:

这样写你的函数:

createSurveyResult(surveyResults) {
  let token = Vue.prototype.$auth.getLocalStorage(
    `${this.activeUser.uuid}_${process.env.NODE_ENV}_${ACCESS_TOKEN}`
  );

  if (token) {
    axiosModified.defaults.headers.common["Authorization"] = `Bearer ${token}`;
  }

  return Promise.all(
    surveyResults.map((payload) =>
      axiosModified.post("/feedback/results/", payload)
    )
  );
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-26
    • 2019-04-18
    • 2018-07-24
    • 2020-08-06
    • 1970-01-01
    • 2020-11-05
    • 2015-05-20
    • 2016-04-18
    相关资源
    最近更新 更多