承诺:节点js中的异步流

时间:2018-06-25 21:10:03

标签: javascript node.js promise es6-promise

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

这可以确保吗?

1 个答案:

答案 0 :(得分:0)

then()内部的代码将被同步执行。

在您的最佳示例中,Z节可能在B节中promise内的代码之前执行。

在您的底部示例中,then()未附加到诺言,因此行不通。

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

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

您想对result做的任何事情都必须在.then()内部进行。