首页 > 解决方案 > 如何检查 NodeJS 程序是否即将存在

问题描述

假设有人实现了不同的 setTimeout 函数:

const setTimeout = (func, ms) => {
  const future = Date.now() + ms;
  while (Date.now() < future) {
    // do nothing
  }
  func();
};

哪个(为了这个问题的简单性)具有与原始界面几乎相同的界面。作为使用它的开发人员,我如何才能验证它没有初始化任何异步代码?

我想知道我的程序在我使用setTimeout调用后是否存在。如果setTimeout使用同步代码实现,则程序将在之后(不久)存在。如果实现setTimeout是异步的,程序只有在异步代码完成后才会存在。

更具体地说,我可以做这样的事情吗?

setTimeout(()=>{},1000);
const isAnyAsyncCodeWillRun = ...;
if(isAnyAsyncCodeWillRun){
   console.log('Program wont exist right now, only in about 1000ms');
} else {
   console.log('Program will exist now');
}

标签: javascriptnode.jsasynchronousevent-loop

解决方案


是的,术语“异步”意味着函数在完成工作之前返回,并且当提供回调时,稍后将调用它。所以你可以使用

let done = false;
let returned = false;
unknownFunction(() => {
    done = true;
    if (returned) console.log("callback is getting called asynchronously");
});
returned = true;
if (done) console.log("callback was called synchronously");

当然,您无法同步确定该函数稍后是否会异步执行某些操作(除非您的环境为此提供了特殊的挂钩)。


推荐阅读