从第一个api获取数据后进行第二个api调用

时间:2019-07-22 10:06:16

标签: javascript reactjs api

我有第一个API调用,它获取了一些数据,一旦我从该api中获取了数据,才需要进行第二个api调用。它必须在系列中而不是并行发生。我们如何在ComponentDidMount反应中做到这一点? 我在听firebase。 让我们假设第一个api给我一个matchId,现在我们需要使用该matchid在第一个api调用之后立即进行第二次调用,而无需任何点击。

让我们假设这是我的第一个firebase调用。

const cardsListener = 
        getDATA()
        .onSnapshot( (doc)=>{
            console.log("doc is ",doc);
            let data = doc.data();
            console.log("data",data);
            this.setState({
                 datainstate:data
            });
        });

4 个答案:

答案 0 :(得分:2)

感谢async/await,您可以等到操作完成。

componentDidMount() {
  this.firstApiCall()    
}

async firstApiCall() {
  await fetch("http://myurl.com", {
     method: 'POST',
     body: JSON.stringify(data), // data can be `string` or {object}!
     headers:{
       'Content-Type': 'application/json'
     }
   })
   .then(res => res.json())
   .then((responseJson) => {
     //if it worked
     this.secondApiCall()
   })
   .catch(error => console.error('Error:', error))
}

secondApiCall() {

}

答案 1 :(得分:0)

您可以通过多种方式执行此操作。我的首选方式是使用异步等待。我将在下面举例说明如何使用它。

        const getData = async() => {
          try {
            const apiCall1 = await axios.get(SOME_URL);
            const apiCall2 = await axios.get(SOME_URL/apiCall1.data.id)
            return apiCall2
          } catch(e) {
            return e
          }
        }

这是一个愚蠢的例子,但希望您能明白这一点。我进行第一个API调用,然后等待响应。然后,我使用第一次调用中的一些数据进行第二次API调用,然后返回。您可以在两者之间做任何想要的逻辑。

您还可以使用回调或Promise,但我认为异步等待更为清晰,而且代码通常更少。

异步等待文档-https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function 承诺文档-https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise 回调文档-https://developer.mozilla.org/en-US/docs/Glossary/Callback_function

答案 2 :(得分:0)

您可以按照以下步骤操作:

componentDidMount() {
  fetch("apiUrl").then(res => {
    //Do whatever you want to do with the response or get the id
    const {id} = res;
    fetch(`apiUrl/${id}`).then(response => {
      // Do anything with the response of the api call here
    }).catch(error => {
      //Thing to do on error
    });
  }).catch(err => {
    //Thing to do on error of 1st api call
  });
}

答案 3 :(得分:-4)

使用回调或Promise