如果您有基于Promise的功能,那么:
function foo() {
return new Promise(function(fulfill, reject) {
// Do some async work, and then...
console.log('a');
fulfill('b');
console.log('c');
});
}
您会注意到c
语句将在fulfill
语句后打印出来,暗示该功能在履行或拒绝时不会中断。这很麻烦,因为大多数逻辑假设函数应该在调用fulfill()
或reject()
后结束。
问题:
安全或标准使用是否只需在return
或fulfill()
来电之前添加reject()
?
function foo() {
return new Promise(function(fulfill, reject) {
// Do some async work, and then...
console.log('a');
return fulfill('b');
console.log('c'); //Does not get printed, as the function has ended execution.
});
}
// Call the function:
foo()
.then(function(response) {
console.log(response); //This is called once the function calls fulfill, will print 'b'
});
使用Promise有什么问题吗?大多数在线承诺信息都没有提及在履行或拒绝之前使用return
语句。另外一个问题是,使用then
和catch
时使用缩进的最常用方法是什么?
答案 0 :(得分:1)
承诺构造函数用于converting APIs that don't return promises to promises。您应该考虑使用提供promisification的库(即使您全面使用本机承诺),因为它提供了一个安全的替代方案,它没有错误处理逻辑的细微错误。
自动宣传也相当快。
这样做非常安全,promise构造函数没有什么特别之处 - 它们只是简单的JavaScript。 Domenic讨论了promise构造函数in his blog的设计。
早期返回是完全安全的(就像任何其他函数一样) - 它在常规异步函数中非常常见。
(另外,在您的示例代码中,您应该只使用Promise.resolve
,但我认为 只是简单,因为它是一个示例。)