【问题标题】:Pass data through promise .then notation using axios使用 axios 通过 promise .then 表示法传递数据
【发布时间】:2021-04-17 19:07:43
【问题描述】:

我需要进行三个 Web 服务调用。后两个调用取决于第一个调用的结果。然后我想用所有三个服务器调用的结果来解决我的承诺。想象一下,我想获得一项特定运动的所有球员。使用这些球员,我想拨打电话以获取他们效力的球队的列表,并且我想拨打电话以获取他们参加过的比赛。它看起来像这样:

static doTheThing(sports) {
    return new Promise((resolve, reject) => {
     axios
        .post("http://localhost:8076/getPlayersForSports", sports)
        .then((res1) => {
          const playerNames = res1.data.map(player => player.name);
          return(axios.all([
            axios.post("http://localhost:8076/getTeams", playerNames),
            axios.post("http://localhost:8076/getGames", playerNames),
          ]));
        }).then(axios.spread((res2, res3) => {
          resolve( 
            res1.data
            res2.data, 
            res3.data)
        }))
        .catch((err)=> {
          reject(err);
        })
    })
  }

我已经走到这一步了。我可以得到一个通过的运动列表的球员列表。我可以从每个播放器对象中获取名称并使用它来调用其他两个 Web 服务(我已经确认在 chrome 开发控制台中返回是正确的)。这就是我卡住的地方。我正在使用 axios.all() 链接后两个命令,然后使用 axios.spread() ,正如我在其他一些响应中看到的那样。我不知道如何通过链传递 res1,以便我可以解决所有三个数据集。

【问题讨论】:

  • 只需将它与数组上的其他承诺一起返回
  • 避免使用Promise constructor antipattern!但最重要的是,你不能一次用三个值解决一个 Promise。但是,您可以使用包含多个值的数组或对象来解决它。

标签: javascript json promise axios


【解决方案1】:

为什么不用firstRes 将它保存在函数内但在承诺链之外的变量中:

static doTheThing(sports) {
    let firstRes;

    return new Promise((resolve, reject) => {
     axios
        .post("http://localhost:8076/getPlayersForSports", sports)
        .then((res1) => {
          const playerNames = res1.data.map(player => player.name);
          firstRes = res1;
          return(axios.all([
            axios.post("http://localhost:8076/getTeams", playerNames),
            axios.post("http://localhost:8076/getGames", playerNames),
          ]));
        }).then(axios.spread((res2, res3) => {
          resolve( 
            firstRes
            res2.data, 
            res3.data)
        }))
        .catch((err)=> {
          reject(err);
        })
    })
  }

【讨论】:

  • 真的,只是为了避免创建变量。如果必须这样做,没有什么能阻止我,但原则上我很好奇是否有一种具体的方法可以将其传递到链中而不是初始化变量。
猜你喜欢
  • 2018-10-12
  • 2016-09-01
  • 2020-06-02
  • 2019-05-10
  • 1970-01-01
  • 2016-11-04
  • 2017-07-02
  • 2018-10-01
  • 2017-07-11
相关资源
最近更新 更多