【问题标题】:Promises Puzzles承诺拼图
【发布时间】:2021-10-15 23:29:19
【问题描述】:

我正在阅读有关 Promises 的博客,它们显示了一个我根本没有得到的问题。 博客是:https://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html

作者提出了 4 个带有图形解决方案的谜题:

谜题#1

doSomething().then(function () {
  return doSomethingElse();
}).then(finalHandler);

谜题 #2

doSomething().then(function () {
  doSomethingElse();
}).then(finalHandler);

谜题#3

doSomething().then(doSomethingElse())
  .then(finalHandler);

谜题#4

doSomething().then(doSomethingElse)
  .then(finalHandler);

这里 doSomething() 和 doSomethingElse 是承诺。

谁能给大家详细解释一下? 在第一个上,我得到了执行顺序。 第二,我不明白为什么 doSomethingElse 和 finalHandler 同时开始和结束。 第三,我不明白为什么 doSomething 和 doSomethingElse 同时开始。 doSomethingElse 不应该从 doSomething 的末尾开始吗? 第四,我什么都没有……

【问题讨论】:

  • 在第一个示例中,finalHandler 正在等待 Promise return doSomethingElse(); <Promise> 解决。第二个它不会等待,因为 return 没有设置为 Promise。它只是立即执行该功能。
  • 那篇博文中解释了一切。

标签: javascript node.js asynchronous


【解决方案1】:

谜题 1

// doSomething() is executed and returns a promise
doSomething().then(function () {
  // when doSomething() executes successfully, execute doSomethingElse() and return the Promise
  return doSomethingElse();
}).then(finalHandler); // final handler will be executed once doSomethingElse has finished, since the promise was returned 

谜题 2

// doSomething() is executed and returns a promise
doSomething().then(function () {
  // when doSomething() executes successfully, execute doSomethingElse()
  doSomethingElse(); // execute doSomethingElse()
  // since there is nothing returned here, the the promise will resolve immediatly, without waiting for doSomethingElse() to complete
}).then(finalHandler); // final handler will be executed immediatly after doSomethingElse() has started to execute, without waiting for a result.

谜题 3

在这个中,两个函数同时启动,因为.then 期望一个函数作为它的第一个参数。 doSomethingElse 是一个函数,但 doSomethingElse() 是一个函数调用。因此它被立即调用,.then()doSomethingElse 的返回值作为第一个参数,这是一个承诺。

doSomething().then(doSomethingElse())
  .then(finalHandler);

谜题 4

与谜题 3 不同,函数 doSomethingElse 被传递给 .then(),而不是谜题 3 中 doSomethingElse 的返回值。 这意味着一旦doSomething 完成,就会调用doSomethingElse

// the code below is a shortcut for doSomething().then(() => doSomethingElse())
doSomething().then(doSomethingElse)
  .then(finalHandler);

函数与函数调用

您需要了解的是函数 (doSomething) 和函数调用 (doSomething()) 之间的区别。

function doSomething() {
  return "something";
}

const func = doSomething;
const value = doSomething();

console.log(func);
console.log(value);

【讨论】:

  • 非常感谢。很清楚。
【解决方案2】:

谜题#1 和#4 以及谜题#2 和#3 相同。

在您的谜题 #2 中,您开始另一个 Promise 并立即返回,无需等待。所以你的 finalHandler 将在 doSomethingElse 启动后立即被调用,而不是在它完成后。如果您愿意,请使用您的谜题 #1

在您的谜题#3 中,您直接传递 doSomethingElse() 返回的已启动 Promise,而不是告诉 js 在 doSomething 解决后调用该函数。如果您想这样做,请这样写 - 这可能有助于避免混淆

doSomething()
  .then(() => doSomethingElse())
  .then(() => finalHandler());

【讨论】:

    猜你喜欢
    • 2015-10-06
    • 2018-06-23
    • 1970-01-01
    • 1970-01-01
    • 2017-05-18
    • 2015-05-12
    • 2016-06-15
    • 2016-07-27
    相关资源
    最近更新 更多