Search code examples
javascriptnode.jspromisees6-promise

Promise: Async flow in node js


Hi I am new to asynchronous programming. I am unable to understand if a promise resolves successfully does the code still be asynchronous. For example: module A has function A() which returns a promise. I require module A in module B and call function A() The code in module B will look like:

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....

So, does this code execute synchronously i.e., first section X then Y and then Z? or do I have to modify it like:

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

Does this ensure that?


Solution

  • Only the code inside the then() will be executed synchronously.

    In your top example, Section Z maybe be executed before the code inside of the promise in section B.

    In your bottom example, the then() is not attached to a promise and thus wouldn't work.

    To make it synchronous, you want to change it to look like this:

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

    Anything you want to do with result has to happen inside .then().