javascript - 如何检查 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');
}
解决方案
是的,术语“异步”意味着函数在完成工作之前返回,并且当提供回调时,稍后将调用它。所以你可以使用
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");
当然,您无法同步确定该函数稍后是否会异步执行某些操作(除非您的环境为此提供了特殊的挂钩)。
推荐阅读
- javascript - JS无法使光标后的图像居中
- arrays - 使用flutter从firestore获取用户数组数据
- raspberry-pi - Raspberry Pi:声音回放适用于 HDMI 和 omxplayer,但不适用于 youtube 视频的 Chrome 浏览器
- python - 如何在 Django 中具有用户模型的 ForeignKey 的模型中保存 ModelFrom 数据?
- javascript - 如何在 Dynamodb 扫描中使用 reduce 查询
- python - Requests error only with one specific website : OS Error 10054 Connection aborted
- python - 库达 10.1。cuDNN 7.6.6 与 tensorflow 1.14 兼容吗?
- python - Pydantic:数据类与 BaseModel
- azure - 将 AzureDevops 指向本地存储库管理器 (Nexus)
- ruby-on-rails - Ruby/Rails - Shrine::Error(存储:存储未在 ImageUploader 上注册)