我应该使用上次承诺后完成的吗



在react native中,未处理的承诺是静默的。过去有一个";未经处理的承诺拒绝;警告,但现在我再也看不到了。有人知道发生了什么?

我发现,如果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参考。

这里已经有了类似的问题,但它已经有5年的历史了,本地项目的反应变化非常快。

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

最新更新