首页 > 解决方案 > 承诺:节点 js 中的异步流

问题描述

嗨,我是异步编程的新手。我无法理解如果承诺成功解决,代码是否仍然是异步的。例如:模块 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....});

这能保证吗?

标签: javascriptnode.jspromisees6-promise

解决方案


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

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

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

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

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

你想做的任何事情result都必须发生在里面.then()


推荐阅读