- 疑问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));
Promise then 返回值 根据then内函数的返回值,then的返回值有不同策略呀
我认为 then函数内是否return 取决于业务
这个是test1-4顺序执行,且如果前面reject时,后面就会不执行,前后有一个明显的依赖关系。
这个同样时test1-4顺序执行,但是如果前面reject,不影响后续执行,这里只关注执行的顺序问题,不关注前者动作是否成功。