可能未处理的承诺拒绝 (id:0) 警告 [英] Possible Unhandled Promise Rejection (id:0) Warning

查看:68
本文介绍了可能未处理的承诺拒绝 (id:0) 警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我的 AsyncStorage 项为空时,我收到以下警告消息可能未处理的承诺拒绝 (id:0)" 所以我的问题是:我如何处理承诺拒绝?

I am getting the following warning message when my AsyncStorage Item is empty "Possible Unhandled Promise Rejection (id:0)" So my question is: How can I handle a promise rejection?

我的代码:

componentDidMount() {
        try {
            // This warning only appears when 'connections' item is empty
            AsyncStorage.getItem('connections').then((token) => {
                token = JSON.parse(token);

                const getSectionData = (dataBlob, sectionId) => dataBlob[sectionId];
                const getRowData = (dataBlob, sectionId, rowId) => dataBlob[`${rowId}`];

                const ds = new ListView.DataSource({
                    rowHasChanged: (r1, r2) => r1 !== r2,
                    sectionHeaderHasChanged: (s1, s2) => s1 !== s2,
                    getSectionData,
                    getRowData,
                });

                const {dataBlob, sectionIds, rowIds} = this.formatData(token);

                this.setState({
                    dataSource: ds.cloneWithRowsAndSections(dataBlob, sectionIds, rowIds),
                });
            });
        }catch(error) {
            console.log(error);
        }
    }

推荐答案

你需要抓住 promise 的拒绝:

You need to catch the reject of the promise:

componentDidMount() {
  // This warning only appears when 'connections' item is empty
  return AsyncStorage.getItem('connections').then((token) => {
    token = JSON.parse(token);

    const getSectionData = (dataBlob, sectionId) => dataBlob[sectionId];
    const getRowData = (dataBlob, sectionId, rowId) => dataBlob[`${rowId}`];

    const ds = new ListView.DataSource({
      rowHasChanged: (r1, r2) => r1 !== r2,
      sectionHeaderHasChanged: (s1, s2) => s1 !== s2,
      getSectionData,
      getRowData,
    });

    const { dataBlob, sectionIds, rowIds } = this.formatData(token);

    this.setState({
      dataSource: ds.cloneWithRowsAndSections(dataBlob, sectionIds, rowIds),
    });
  }).catch(error => {
    console.log(error);
  })
}

这篇关于可能未处理的承诺拒绝 (id:0) 警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆