【问题标题】:Promise: Async flow in node js承诺:节点 js 中的异步流
【发布时间】:2018-06-26 05:19:21
【问题描述】:

您好,我是异步编程的新手。我无法理解如果承诺成功解决,代码是否仍然是异步的。 例如: 模块 A 具有返回承诺的函数 A()。 我需要模块 B 中的模块 A 并调用函数 A() 模块 B 中的代码如下所示:

Section X: some code in module B
Section Y: ModuleA.functionA().then((result) => {
           somevariableInModuleB = result; 
            // assign the result from A() to some variable in module B.
           // some more logic goes here....
        });
Section Z: some more code in module B....

那么,这段代码是否同步执行,即先是 X 部分,然后是 Y 部分,然后是 Z 部分? 还是我必须像这样修改它:

Section X: some code in module B
Section Y: ModuleA.functionA().then((result) => {somevariableInModuleB = result;})
Section Z: .then(() => {some more code in module B....});

这能保证吗?

【问题讨论】:

  • 其中一些代码在另一个模块中的事实是完全不相关的;你想用result做的所有事情都必须在.then()内部发生。

标签: javascript node.js promise es6-promise


【解决方案1】:

只有then() 中的代码会被同步执行。

在您的顶级示例中,Z 部分可能会在 B 部分中承诺内的代码之前执行。

在您的底部示例中,then() 未附加到承诺,因此不起作用。

要使其同步,您需要将其更改为如下所示:

Section X: some code in module B
Section Y: ModuleA.functionA().then((result) => {
  somevariableInModuleB = result;
  some more code in module B....
})

您想对result 执行的任何操作都必须在.then() 内部进行。

【讨论】:

  • 感谢@Davia,以防我在 Y 部分完成了所有逻辑结果。我还需要将 Z 部分的代码放在里面吗?我的理解是,如果必须使用 result 或 somevariableInModuleB 一切都在 then() 或以下 then() 中。
猜你喜欢
  • 2016-01-08
  • 2018-09-26
  • 2021-11-01
  • 1970-01-01
  • 2016-09-08
  • 2023-04-06
  • 2021-10-03
  • 2017-07-23
  • 1970-01-01
相关资源
最近更新 更多