- 疑问0:then的第一个(参数)函数中 只有return promise才是最佳实践吗?
- 疑问1(基于疑问0):是最佳实践的话,设计之初,为什么不将返回值 自动转为promise,而无需考虑程序员 有无return?
- 疑问2(基于疑问0):不是最佳实践的话,那么不写return 或 return一个非promise值 有什么实际意义? 另外这种情况能否用return一个promise来代替掉(即代码运行结果不变)。
摘自 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises
// Bad example! Spot 3 mistakes!
doSomething().then(function(result) {
doSomethingElse(result) // Forgot to return promise from inner chain + unnecessary nesting
.then(newResult => doThirdThing(newResult));
}).then(() => doFourthThing());
// Forgot to terminate chain with a catch!
The first mistake is to not chain things together properly. This happens when we create a new promise but forget to return it. As a consequence, the chain is broken, or rather, we have two independent chains racing. This means?doFourthThing()
won't wait for ? doSomethingElse()
or doThirdThing()
to finish, and will run in parallel with them, likely unintended. Separate chains also have separate error handling, leading to uncaught errors.
The second mistake is to nest unnecessarily, enabling the first mistake. Nesting also limits the scope of inner error handlers, which—if unintended—can lead to uncaught errors. A variant of this is the promise constructor anti-pattern, which combines nesting with redundant use of the promise constructor to wrap code that already uses promises.
The third mistake is forgetting to terminate chains with catch
. Unterminated promise chains lead to uncaught promise rejections in most browsers.
doSomething()
.then(function(result) {
return doSomethingElse(result);
})
.then(newResult => doThirdThing(newResult))
.then(() => doFourthThing())
.catch(error => console.error(error));
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…