【问题标题】:Should I use .done after the last promise?我应该在最后一个承诺之后使用 .done 吗?
【发布时间】:2020-07-17 23:46:25
【问题描述】:

在 react-native 中,未处理的 Promise 是沉默的。曾经有一个“未处理的承诺拒绝”警告,但现在我看不到它了。有人知道这是怎么回事吗?

我发现将 .done() 放在 promise 之后,如果 promise 被拒绝会引发错误。

假设我有一个永远不会被拒绝的承诺,我是否应该在它后面加上 .done 以检测可能的错误?

const asyncFunc = async () => {
   const a = null;

  return a.undefinedField;
}

<Button onPress={() => asyncFunc()} />
<Button onPress={() => asyncFunc().done()} />

我正在使用 react-native,它使用 promise (Github)

我指的是这里解释的那个:Promise API Reference

已经有一个类似的问题here,但是已经5年了,react-native项目变化很快。

【问题讨论】:

标签: javascript react-native promise


【解决方案1】:

Promise 没有done 功能。

您可以在catch 中发现可能的错误,并在finally 中放置无论成功与否都要做的事情。

例如:

const asyncFunc = () => {
   return new Promise((resolve) => {
      throw new Error('Error');
      resolve('Result');
   })
}
asyncFunc().then(res => {
  console.log(res);
}).catch(e => {
  console.error(e);
}).finally(() => {
  console.log('This will be executed in regardless of success');
});

如果您使用的是 async - await,您可以像其他功能一样使用 try-catch:

const asyncFunc = () => {
   return new Promise((resolve) => {
      throw new Error('Error');
      resolve('Result');
   })
}

const executeAsyncFunc = async () => {
  try {
    await asyncFunc();
  } catch (e) {
    console.error(e);  
  } finally {
    console.log('This will be executed in regardless of success');
  }
};

executeAsyncFunc();

【讨论】:

  • 他们确实有,我在这里说的是 react-native。
猜你喜欢
  • 2021-01-04
  • 1970-01-01
  • 1970-01-01
  • 2023-03-15
  • 1970-01-01
  • 2012-08-18
  • 1970-01-01
  • 2015-08-10
相关资源
最近更新 更多