我可以暂停执行功能,直到在节点中收到一些值吗?

时间:2019-02-10 19:39:02

标签: javascript node.js asynchronous synchronous

有没有一种方法可以在执行过程中挂起/暂停该函数,然后在节点js处理完几件事(通过socket.io从用户输入的数据)后继续执行?我知道这是不好的做法,需要使用Promise,async / await等。但是,根据我程序的功能,我需要以这种方式进行处理。

我共享代码的原始问题在这里:Node application interactively get user input from react front end by pausing the current execution

4 个答案:

答案 0 :(得分:1)

...“在执行过程中暂停功能”不太可能真正描述您想要发生的事情。我假设您正在运行一些异步代码,这些代码负责使您的程序达到“处理了一些事情”的地步……因此您的代码看起来像

  var a_few_things_have_been_handled = false;
  handle_a_few_things(); 
  // which returns immediately but has a side effect of 
  // effectively setting a_few_things_have_been_handled to true

  while(!a_few_things_have_been_handled) {
    // do nothing just wait...
    // actually you want to yield to asynchronous threads
    // but you can't do it like this
  }

  the_rest_of_your_program();

不幸的是,这不是该语言的工作原理……您必须使用Promises或类似的异步流控制构造来重组程序流,以明确地了解顺序程序流。

答案 1 :(得分:0)

您可以在setTimeout()调用中包装函数的“第二个块”,如下所示:

function f()
{
  statement1;
  setTimeout(() => {
    statement2;
  }, 1000);
}

答案 2 :(得分:0)

您可以使用javascript中的异步/等待功能来做到这一点。重写任何基于回调的函数以使用Promises,然后等待其解决。

答案 3 :(得分:0)

您可以使用asyncawaitPromise来做到这一点。

function func1(){
  console.log("function 1 is finished")
}
function func2(){
  console.log("function 2 is finished")
}

const thingsHandled = new Promise((res,rej) => {
    func1();
    func2();
    console.log("Every function is done")
    res();
})
   
async function main(){
    await thingsHandled;
    console.log("function is continued");
}
main();

相关问题