此功能:
function print(){
console.log('num 1')
setTimeout(() => {
global.name = 'max'
console.log('num 2')
},9000);
console.log('num 3');
}
print();
console.log(global.name)
为此而骄傲:
num 1
num 3
undefined
num 2
我需要:
num 1
global.name
= max
num 2
num 3
console.log(global.name)
max
而不打印undefined
我用python编写了这段代码,并逐行执行 因为没有所谓的同步和异步。
我需要像python(一行一行)那样执行这段代码
答案 0 :(得分:0)
JavaScript代码逐行执行。如果您想执行一段代码,则仍然需要将给定的行放入超时中,如下所示:
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();
答案 1 :(得分:0)
在JavaScript中使用同步性最易读的方式是使用异步函数。让您了解它的外观:
// 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))
}
您可以在此处了解有关异步/等待的更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function