首页 > 解决方案 > 如何在 React Native 中的前一个函数完成后启动函数

问题描述

我有个问题。我知道我可以使用 Promise 来解决这个问题,但我不明白如何在我的情况下使用它们。我只想id从另一个文件中的一个函数中获取(我们称之为callApi),然后用它id来调用另一个函数callApi2。问题是 callApi2 在 apiCall 完成之前运行。

ApiCariIdAktor = {
  cariIdAktor: () => {
    const apikey = APP_CONSTANT.api_key;
    const url = `https://api.themoviedb.org/3/search/person?api_key=${apikey}&language=en-US&query=iko%20uwais&page=1&include_adult=false`;
    let id = 0;
    fetch(url)
      .then((response) => response.json())
      .then((responseJson) => {
        responseJson.results[0].id
      })
      .catch((error) => {
        console.log(error)
      })
    return 10;
  }
}

setID() {
  this.state.id = ApiCariIdAktor.cariIdAktor();
}

async componentDidMount() {
  this.setID();
  await new Promise(resolve => {
    setTimeout(resolve, 1000);
  });
  this.panggilApi2();
}

标签: javascriptreact-nativepromisereact-native-android

解决方案


推荐阅读