![](/img/trans.png)
[英]Access NSE option chain API from Firebase Functions using axios
[英]How do I access previous promise response in a .then() chain in axios?
我需要访问 responseA 才能访问链式请求中的字段值。 怎样才能优雅地做到这一点?
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);
});
更新:我可能应该提到在我的 first.then() 中我返回了 another.network 请求。 而且它必须按顺序发生。
第一个.then()
块内部发生了什么? 从理论上讲,您可以将您需要的值从responseA返回到第二个.then()
块,因为您从第一个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
您可以使用Promise.all
:
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('https://api.openweathermap.org/geo/1.0/direct?q=' + req.body.city + '&limit=1&appid=e43ace140d2d7bd6108f3458e8f5c')
.then(
(response1) => {
let output = response1.data;
axios.get('https://api.openweathermap.org/data/2.5/weather?lat=' + output[0].lat + '&lon=' + output[0].lon + '&appid=e43ace1d1640d2d7bd61058e8f5c')
.then((weatherdd) => {
res.render('index.twig', { weatherdata: weatherdd.data, cityname: req.body.city, todaydatex: todayDate });
})
}
)
.catch(
err => {
res.send(err)
}
);
提示:如您所见,我正在使用从第一个请求返回的 response1,然后用 output 定义一个局部变量,最后在我的下一个 HTTP 请求中使用数据(例如:output[0].lat)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.