【发布时间】: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