问题
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:
- print
num 1
- wait untill the 9 seconds
- set the
global.name
=max
- print
num 2
- print
num 3
console.log(global.name)
- print
max
and notundefined
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