Node js在完成多行代码之前执行函数 [英] Node js execute function before complete multiple lines of code

查看:109
本文介绍了Node js在完成多行代码之前执行函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此功能:

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

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

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

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

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

推荐答案

在JavaScript中使用同步性最易读的方法是使用异步函数.让您了解它的外观:

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))
}

您可以在此处了解有关异步/等待的更多信息: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/async_function

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

这篇关于Node js在完成多行代码之前执行函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆