Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
638 views
in Technique[技术] by (71.8m points)

javascript - Pass data through promise .then notation using axios

I need to make three web service calls. The second two calls depend on the results of the first. Then I want to resolve my promise with the results of all three server calls. Imagine I want to get all the players of a given sport. Using those players, I want to make a call to get a list of teams they play on, and I want to make a call to get the games they've played in. It looks something like this:

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

I have gotten this far. I can get a list of players for a passed in list of sports. I can get the name off of every player object and use it to call the other two web services (I have confirmed the return is correct in the chrome dev console). This is where I am stuck. I am using axios.all() to chain the second two commands and then axios.spread() as I have seen in some other responses. I cant figure out how to pass res1 through the chain so that I can resolve with all three data sets.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Why not save it in a variable within the function but outside the promise chain like this with 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);
        })
    })
  }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...