Node js在完成多行代码之前执行功能

时间:2019-09-03 15:22:39

标签: javascript node.js chatbot watson-assistant watson-discovery

此功能:

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

我需要:

  1. 打印num 1
  2. 等到9秒钟
  3. 设置global.name = max
  4. 打印num 2
  5. 打印num 3
  6. console.log(global.name)
  7. 打印max而不打印undefined

我用python编写了这段代码,并逐行执行 因为没有所谓的同步和异步。

我需要像python(一行一行)那样执行这段代码

2 个答案:

答案 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