oto*_*ong 0 javascript promise axios
我想使用返回objectId数组列表的axios来获取API.在我获得列表objectId之后,我想使用promise获取对象的细节
我想到这样的事情
var objectDetail = [];
axios.get('apiendpoint/')
.then((response) => {
var listOfObjectId = response.data;
var chain = Promise.resolve()
for (var objectId of listOfObjectId) {
chain = chain.then(axios.get(`apiendpoint/${objectId}`)
.then((response) => {
objectDetail.push(response.data);
})
);
}
return chain;
}).then((chain) => {
console.log(chain);
return chain;
})
Run Code Online (Sandbox Code Playgroud)
上面的代码返回undefined,promise链对象不传递给then方法调用.我的方法错了还是我错过了什么?谢谢
这是我读过的一些堆栈,可能是相关的:
该承诺链条被传递到最后.then,但承诺链不返回任何东西:看你的
.then((response) => {
objectDetail.push(response.data);
})
Run Code Online (Sandbox Code Playgroud)
该功能不会返回任何内容.如果你想objectDetail在链的末尾使用而不引用外部变量,return它也是:
.then((response) => {
objectDetail.push(response.data);
return objectDetail;
})
Run Code Online (Sandbox Code Playgroud)
但请注意
}).then((chain) => {
console.log(chain);
return chain;
})
Run Code Online (Sandbox Code Playgroud)
有点多余 - 除非你只是为了log结果而这样做,最好只是完全放弃它.
如果您使用的话,您的代码会更清晰Promise.all:
axios.get('apiendpoint/')
.then(({ data }) => Promise.all(
data.map(objectId => (axios.get(`apiendpoint/${objectId}`)
.then(res => res.data)
))
));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
107 次 |
| 最近记录: |