【问题标题】:Return object from Promise.all(...)从 Promise.all(...) 返回对象
【发布时间】:2021-11-21 15:05:48
【问题描述】:

我正在使用 API 根据机场代码检索(几个机场的)数据...

async function airpt(codes){
    const airportCredential = {
      "method": "GET",
      "headers": {
        "x-rapidapi-host": "airport-info.p.rapidapi.com",
        "x-rapidapi-key": "xxxx"
      }
    }

    return Promise.all(
      codes
      .map(code =>
        fetch("https://airport-info.p.rapidapi.com/airport?iata="+code,airportCredential)
        .then(r => r.json())
      )
    );

  }

airpt(['JFK','LAX'] 这样的调用会产生一个数组,其结果如下:

 Array(2)
0: {id: 3406, iata: 'JFK', icao: 'KJFK', name: 'John F. Kennedy International Airport', location: 'New York City, New York, United States', …}
1: {id: 4044, iata: 'LAX', icao: 'KLAX', name: 'Los Angeles International Airport', location: 'Los Angeles, California, United States', …}
length: 2

这很好。但是我如何从这个函数返回一个(单个)承诺,并将所有数据打包到一个对象中,该对象使用输入 codes 作为键?

我知道如何将数组转换为对象:

array.reduce((obj, item) => {
    return {
      ...obj,
      [item['iata']]: item,
    };
  }, {});

我知道该怎么做,在解决了Promise.all() 之后使用.then(...)。但是,我希望将重新打包到一个对象中作为异步函数的一部分。

【问题讨论】:

  • airpt 返回一个承诺。您要么需要在使用 reduce 之前等待它,要么将 reduce 放在下面的 then 中。
  • "我知道如何使用 .then(...) 来做到这一点,但是我想将其作为异步函数的一部分。" - 所以只需使用 await 代替.then(…)?
  • @evolutionxbox ...感谢您的快速反应。我相信我了解async/awaitthen 的基础知识......但是我没有找到从airpt 返回Promise 对象的好方法。
  • 你可以做return Promise.all(...).then(array => array.reduce(...))

标签: javascript asynchronous promise.all


【解决方案1】:

你似乎已经有了你需要的部分,所以希望你只需要看到它们放在一起。下面是在 promise.all 之后执行一些额外代码并基于数组返回一个对象的样子:

async function airpt(codes){
  const airportCredential = {
    "method": "GET",
    "headers": {
      "x-rapidapi-host": "airport-info.p.rapidapi.com",
      "x-rapidapi-key": "xxxx"
    }
  }

  const array = await Promise.all(
    codes
    .map(code =>
      fetch("https://airport-info.p.rapidapi.com/airport?iata="+code,airportCredential)
      .then(r => r.json())
    )
  );

  return array.reduce((obj, item) => {
    return {
      ...obj,
      [item['iata']]: item,
    };
  }, {});
}

【讨论】:

  • 谢谢,这样就可以了!就像@derpirscher 建议return Promise.all(...).then(array => array.reduce(...))
猜你喜欢
  • 2019-07-17
  • 2021-03-18
  • 2019-02-04
  • 2017-02-26
  • 2020-11-05
  • 1970-01-01
  • 2020-08-06
  • 2018-02-20
  • 2018-12-05
相关资源
最近更新 更多