Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

promise 链式调用中,then的第一个(参数)函数中为什么需要手动 return 一个 promise,而不是自动?

  • 疑问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));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Promise then 返回值 根据then内函数的返回值,then的返回值有不同策略呀

doesn't return anything, the promise returned by then gets resolved with an undefined value.

returns an already fulfilled promise, the promise returned by then gets fulfilled with that promise's value as its value.

我认为 then函数内是否return 取决于业务

test1().then(() => 
    test2()
).then(() => 
    test3()
).then(() => 
    test4()
)

这个是test1-4顺序执行,且如果前面reject时,后面就会不执行,前后有一个明显的依赖关系。

test1().then(() => { 
    test2() 
}).then(() => {
    test3()
}).then(() => {
    test4()
})

这个同样时test1-4顺序执行,但是如果前面reject,不影响后续执行,这里只关注执行的顺序问题,不关注前者动作是否成功。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...