我需要调用多个端点,每次调用都取决于上一次调用的结果。
return http.get('url1')
.then(response1 => {
return response1.data
})
.then(data => {
http.get('url2' + data)
.then(response2 => {
return response2.data
}) // etc ... until the 'nth url'
})
它可以嵌套。有没有办法将其展平,也许使用生成器?
最佳答案
promise 是为了扁平化:
return http.get('url1').then(response1 => {
return response1.data
}).then(data => {
return http.get('url2' + data);
}).then(response2 => {
return http.get('url3' + response2.data);
}) // ...etc
如果您的 JavaScript 引擎支持 async
/await
,则可以在 async
函数中使其更短且更易读:
async function demo() {
const response1 = await http.get('url1');
const response2 = await http.get('url2' + response1.data);
const response3 = await http.get('url3' + response2.data);
// ...
return responseN;
}
...然后调用它:
demo().then(response => {
console.log(response);
// ...etc
});
关于javascript - 无需过多嵌套即可调用多个 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47102712/