Node js execute function before complete multiple lines of code

十年热恋 提交于 2020-01-25 07:19:29

问题


This function:

function print(){
  console.log('num 1')

  setTimeout(() => {
    global.name = 'max'
    console.log('num 2')
  },9000);

  console.log('num 3');
}
print();
console.log(global.name)

is priting this:

num 1
num 3
undefined
num 2

And I need to:

  1. print num 1
  2. wait untill the 9 seconds
  3. set the global.name = max
  4. print num 2
  5. print num 3
  6. console.log(global.name)
  7. print max and not undefined

I wrote this code in python and it executese line by line because there is nothing called sync and async.

I need this code executed like python(line by line)


回答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";

function print() {
    console.log('num 1');

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

    }, 900);


}

print();



回答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 () => {

  async function print(){
    console.log('num 1')

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

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

    console.log('num 3');
  }

  // wait for the print function to finish
  await print();

  console.log(global.name)

})();

// Little utility function
function sleep(time) {
  return new Promise(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



来源:https://stackoverflow.com/questions/57774652/node-js-execute-function-before-complete-multiple-lines-of-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!