簡體   English   中英

承諾:節點js中的異步流程

[英]Promise: Async flow in node 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....});

這樣可以確保嗎?

只有then()內部的代碼將被同步執行。

在您的最佳示例中,Z節可能在B節中promise內的代碼之前執行。

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

為了使其同步,您需要將其更改為如下所示:

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

您想要對result任何操作都必須在.then()內部進行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM