Javascript 如何访问axios中.then()链中以前的承诺响应?
我需要访问responseA,以便沿着链接请求进一步访问字段值。怎样才能做到优雅呢Javascript 如何访问axios中.then()链中以前的承诺响应?,javascript,amazon-s3,axios,Javascript,Amazon S3,Axios,我需要访问responseA,以便沿着链接请求进一步访问字段值。怎样才能做到优雅呢 axios.get(`/endpoint`) .then((responseA) => { // Do something with responseA return axios.put(signedUrl, file, options); }) .then((resp
axios.get(`/endpoint`)
.then((responseA) => {
// Do something with responseA
return axios.put(signedUrl, file, options);
})
.then((responseB) => {
// Do something with responseA & responseB
})
.catch((err) => {
console.log(err.message);
});
更新:我应该在我的第一篇文章中提到这一点。然后()我返回另一个网络请求。它必须按顺序发生。在第一个
块中发生了什么。然后()?理论上,您可以将所需的值从responseA返回到第二个.then()
块,因为从第一个然后块返回的任何值都可以作为responseB使用。换句话说,它看起来是这样的:
axios.get(`/endpoint`)
.then((responseA) => {
// additional request/logic
const moreData = someFunction()
return { responseAdata: responseA.dataYouWant, moreData: moreData }
})
.then((responseB) => {
// now responseA values will be available here as well, e.g.
responseB.responseAdata
// Do something with responseA & responseB
})
.catch((err) => {
console.log(err.message);
});
第一个.then()
块中发生了什么?理论上,您可以将所需的值从responseA返回到第二个.then()
块,因为从第一个然后块返回的任何值都可以作为responseB使用。换句话说,它看起来是这样的:
axios.get(`/endpoint`)
.then((responseA) => {
// additional request/logic
const moreData = someFunction()
return { responseAdata: responseA.dataYouWant, moreData: moreData }
})
.then((responseB) => {
// now responseA values will be available here as well, e.g.
responseB.responseAdata
// Do something with responseA & responseB
})
.catch((err) => {
console.log(err.message);
});
你有很多选择可以做到这一点
1) 打破锁链
let promiseA = axios.get(`/endpoint`)
let promiseB = promiseA.then((responseA) => {
// Do something with responseA
})
return Promise.all([promiseA, promiseB]).then(function([responseA, responseB]) {
// Do what you must
});
2) 使用等待
let responseA = await axios.get('/endpoint/')
// You can figure out the rest
你有很多选择可以做到这一点
1) 打破锁链
let promiseA = axios.get(`/endpoint`)
let promiseB = promiseA.then((responseA) => {
// Do something with responseA
})
return Promise.all([promiseA, promiseB]).then(function([responseA, responseB]) {
// Do what you must
});
2) 使用等待
let responseA = await axios.get('/endpoint/')
// You can figure out the rest
您可以使用承诺。所有:
axios.get(`/endpoint`)
.then(
responseA =>
Promise.all([
responseA,
axios.get("/endpointB")
])
)
.then(
([responseA,responseB]) => {
console.log(responseA,responseB);
})
.catch((err) => {
console.log(err.message);
});
您可以使用承诺。所有:
axios.get(`/endpoint`)
.then(
responseA =>
Promise.all([
responseA,
axios.get("/endpointB")
])
)
.then(
([responseA,responseB]) => {
console.log(responseA,responseB);
})
.catch((err) => {
console.log(err.message);
});
那些“做点什么”的部分到底是什么?responseB
是否来自由responseA
确定的某个操作,或者它们是独立的?在承诺链之外定义一个变量,并将responseA分配给我,或者使用更具命令性的async/await样式。这些“做点什么”部分到底是什么?responseB
是否来自由responseA
确定的某个操作,或者它们是独立的?在承诺链之外定义一个变量,并将responseA分配给我,或者使用更具命令性的async/await样式。您可以使用