在继续使用JavaScript之前等待函数运行

时间:2017-07-23 13:44:42

标签: javascript reactjs asynchronous react-native promise

我有一个函数fetchItems(),可以从API中提取项目。

在React中,我想设置一个状态,在运行fetchItems()之后,我想再次设置状态。

现在,我就是这样做的

onRefresh() {
  this.setState({
    refreshing: true
  }, () => {
    this.props.fetchItems();
    this.setState({
      refreshing: false
    });
  });
}

但由于它不是异步调用的,所以在再次设置状态之前,它不会等待fetchItems()运行。

我的函数fetchItems()看起来像这样

export function fetchItems() {
  return dispatch => {
    dispatch(requestItems());

    return fetch(API_URL, {
      method: 'GET',
      headers: {
        Accept: 'application/json',
      }
    })
    .then(response => response.json())
    .then(json => dispatch(receiveItems(json)))
    .catch(err => dispatch(failFetchItems()))
  };
};

我想我必须使用Promises。

2 个答案:

答案 0 :(得分:0)

您是否可以使用async/await表示法使代码异步? async/await允许您暂停代码执行,直到Promise结算,如果等待的表达式不是Promise,则会将其转换为Promise

onRefresh = async () => {
  await this.setState({ refreshing: true });
  await this.props.fetchItems();
  await this.setState({ refreshing: false });
}

个人而言,我一直在使用它来使我的代码异步。

如果您想学习这种表示法,可以使用以下链接:

Blog post about async/await

async/await explanation

答案 1 :(得分:0)

确保fetchItems返回一个承诺(看起来确实如此),然后像这样调用第二个setState

this.props.fetchItems().then(() => this.setState({refreshing: false}))