Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/415.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 从第一个api获取数据后进行第二个api调用_Javascript_Reactjs_Api - Fatal编程技术网

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

Javascript 从第一个api获取数据后进行第二个api调用,javascript,reactjs,api,Javascript,Reactjs,Api,我有第一个API调用,它会给我一些数据,一旦我从这个API中得到了数据,我只需要进行第二个API调用。它必须在系列中发生,而不是并行发生。我们如何在react ComponentDidMount中实现这一点? 我在听firebase。 让我们假设第一个api给我一个matchId,现在我们需要使用这个matchId在第一个api调用之后进行第二次调用,而不需要单击 让我们假设这是我第一次调用firebase const cardsListener = getDATA()

我有第一个API调用,它会给我一些数据,一旦我从这个API中得到了数据,我只需要进行第二个API调用。它必须在系列中发生,而不是并行发生。我们如何在react 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
            });
        });

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

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

异步等待文档- 承诺文件-
回调文档-

您可以遵循以下内容:

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

我是从firebase而不是https收听的。