Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.6k 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...