简体   繁体   English

使用 promise.all 从两个 api 获取数据

[英]getting data from two api using promise.all

I would like to get data from two API.我想从两个 API 获取数据。 in the firest call (getDatafromGeonames) I want to get latitude and longitude then I want to pass them as parameters to the second call (getWaetherData) to get weather information then I want to store the result and pass to my endpoint在最火的调用(getDatafromGeonames)中,我想获取纬度和经度,然后我想将它们作为参数传递给第二个调用(getWaetherData)以获取天气信息,然后我想存储结果并传递给我的端点

Here is my try:这是我的尝试:

const res1 =   getDatafromGeonames(geonameAPIURL,city,geonamesKey).then(res =>{
          getWaetherData(res.address.lat, res.address.lng)})
  Promise.all([res1]).then((res)=>{
    //do somthing 
    console.log(res);
  })

a screenshot of the result:结果截图:

I don't know why it is jumping to then and printing Undefined before it is executing getWaetherData?我不知道为什么它会在执行 getWaetherData 之前跳转到 then 并打印 Undefined? How can I get data from the first API then use these data to get weather info then do something with these data如何从第一个 API 获取数据,然后使用这些数据获取天气信息,然后对这些数据进行处理

thanks a lot:)多谢:)

Promise.all only works for Promises you can run in parallel, you have to run them in sequence instead: Promise.all仅适用于可以并行运行的 Promise,您必须按顺序运行它们:

getDataFromGeonames(geonameAPIURL, city, geonamesKey)
  .then((res) => getWeatherData(res.address.lat, res.address.lng))
  .then((res) => {
    // do something
    console.log(res);
    return res;
  });

Promise.all(promises[]) method is meant to execute some logic when all promises[] has been executed. Promise.all(promises[])方法旨在在所有promises[]都已执行时执行一些逻辑。 This would be helpful if you have 2 independant async calls and you want to do something after both of them has been executed.如果您有 2 个独立的异步调用,并且您想在它们都执行后执行某些操作,这将很有帮助。

By what you have described, seems that the second API call you have to do needs the result of the first API call, so the promise operator you should use is .then() .根据您的描述,您必须执行的第二个 API 调用似乎需要第一个 API 调用的结果,因此您应该使用的 promise 运算符是 .then .then()

const waetherData = getDatafromGeonames(geonameAPIURL,city,geonamesKey)
.then(res => getWaetherData(res.address.lat, res.address.lng))

or, in EMS6 style:或者,在 EMS6 样式中:

const getWaetherData = async (geonameAPIURL, city, geonamesKey) => {
      const geodata = await getDatafromGeonames(geonameAPIURL,city,geonamesKey);
      return await getWaetherData(geodata.address.lat, geodata.address.lng)
}

I have put this last code into a method because if you want to use await operator you need to be in a async context.我已将最后一段代码放入一个方法中,因为如果您想使用await运算符,您需要处于async上下文中。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM