简体   繁体   English

如何在 axios 的 a.then() 链中访问之前的 promise 响应?

[英]How do I access previous promise response in a .then() chain in axios?

I need access to responseA to get access to a field value further along the chained request.我需要访问 responseA 才能访问链式请求中的字段值。 How can that be done elegantly?怎样才能优雅地做到这一点?

  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);
            });

UPDATE: I should probably mention that in my first.then() I return another.network request.更新:我可能应该提到在我的 first.then() 中我返回了 another.network 请求。 And it has to happen in sequence.而且它必须按顺序发生。

What is happening inside the first .then() block? 第一个.then()块内部发生了什么? In theory, you could return the values you need from responseA to the second .then() block, as whatever you return from the first then block will be available as responseB. 从理论上讲,您可以将您需要的值从responseA返回到第二个.then()块,因为您从第一个then块返回的任何内容都将作为responseB可用。 In other words, it would look something like this: 换句话说,它看起来像这样:

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);
        });

You have a number of options to do this. 您可以通过多种选择来执行此操作。

1) Break the chain 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) Use await 2)使用等待

let responseA = await axios.get('/endpoint/')
// You can figure out the rest

You can use Promise.all : 您可以使用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);
});

If anyone is still facing problem then try as below:如果有人仍然面临问题,请尝试以下操作:

  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)
            }
        );

Hint: As You can see I am using response1 which is returned from the first request and then defined a local variable with output and finally using the data in my next HTTP request (eg: output[0].lat)提示:如您所见,我正在使用从第一个请求返回的 response1,然后用 output 定义一个局部变量,最后在我的下一个 HTTP 请求中使用数据(例如:output[0].lat)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 axios 从 Firebase 函数访问 NSE 选项链 API - Access NSE option chain API from Firebase Functions using axios 如何从 firebase 实时数据库访问双重嵌套响应? - How do i access a double nested response from firebase realtime database? 如何 Promise 链接多个 google.charts.setOnLoadCallback 的? - How to Promise chain multiple google.charts.setOnLoadCallback's? 如何使用 NextJs API、Firebase Firestore、axios 和 TypeScript 从 Firebase 集合中获取数据? - How do I get data from Firebase collection using NextJs API, Firebase Firestore, axios and TypeScript? 我如何等待 FireBase Kotlin Android Studio 的回复 - how do I wait for a response from FireBase Kotlin Android Studio 如何从未经身份验证的 Cognito 身份获取访问令牌 - How do I obtain an Access Token from an Unauthenticated Cognito Identity 如何访问我的 Python 脚本生成的网页? - How do I access the webpage that my Python script makes? 如何加载以前登录的用户? - How can I load the previous signed in user? 如何在 msal 中使用刷新令牌更新我的访问令牌? - How do I update my access token with a refresh token in msal? firestore 中有一个文档在创建时有一个 ID_number 字段。 如果我想创建另一个文档,如何使它的ID等于之前的ID+1? - There is a doc in firestore that has a ID_number field when created. If I want to create another doc, how do I make its ID equal to the previous ID+1?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM