繁体   English   中英

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

[英]making second api call after getting data from the first api

我有第一个 API 调用,它为我获取了一些数据,一旦我从这个 api 获取了数据,那么我才需要进行第二个 api 调用。 它必须连续发生,而不是并行发生。 我们如何在 React ComponentDidMount 中做到这一点? 我在听 firebase 。 让我们假设第一个 api 给我一个 matchId,现在我们需要使用这个 matchid 在第一个 api 调用之后进行第二次调用而没有任何 click 。

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

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

感谢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() {

}

有很多方法可以做到这一点。 我的首选方法是使用异步等待。 我将在下面举例说明您将如何使用它。

        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 调用,然后返回。 你可以在这之间做任何你想做的逻辑。

您也可以使用回调或承诺,但我认为 async await 更清晰,通常代码更少。

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

你可以遵循这样的事情:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM