Skip to content Skip to sidebar Skip to footer

Node Js Execute Function Before Complete Multiple Lines Of Code

This function: function print(){ console.log('num 1') setTimeout(() => { global.name = 'max' console.log('num 2') },9000); console.log('num 3'); } print(); con

Solution 1:

Javascript code is executed line by line. If you wanna execute pieces of code you still need to put the given lines into the timeout like this:

let name = "Unknown";

functionprint() {
    console.log('num 1');

    setTimeout(() => {
        this.name = 'max';
        console.log('num 2');
        console.log('num 3');
        console.log(this.name);

    }, 900);


}

print();

Solution 2:

The most readable way to work with synchronicity in JavaScript is with async functions. To give you an idea of what it can look like:

// To simulate the function you're going to use the snippet in
(async () => {

  asyncfunctionprint(){
    console.log('num 1')

    // await stops the execution until the setTimeout in sleep is done (non blocking)awaitsleep(9000);

    global.name = 'max'console.log('num 2')

    console.log('num 3');
  }

  // wait for the print function to finishawaitprint();

  console.log(global.name)

})();

// Little utility functionfunctionsleep(time) {
  returnnewPromise(resolve =>setTimeout(resolve, time))
}

You can read more about async/await here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

Post a Comment for "Node Js Execute Function Before Complete Multiple Lines Of Code"