[英]Sleep in Node.js
Assumed that there is no "native" way to achieve this, my solution-like was假设没有“本地”方式来实现这一点,我的解决方案是
sleep = function(time) {
var stop = new Date().getTime();
while(new Date().getTime() < stop + time) {
;
}
return new Promise((r,_)=> r())
}
So doing sleep(1000*3).then(()=>console.log("awake"))
it will sleep 3 seconds and then resolve the Promise
:所以做sleep(1000*3).then(()=>console.log("awake"))
它会睡 3 秒然后解析Promise
:
(be aware that it will freeze this page one sec.) (请注意,它会冻结此页面一秒钟。)
sleep = function(time) { var stop = new Date().getTime(); while (new Date().getTime() < stop + time) {; } return new Promise((r, _) => r()) } console.log("sleeping...") sleep(1000 * 1).then(() => console.log("awake"))
Assumed that this will run in the main thread it will freeze the main process so that doing假设这将在主线程中运行,它将冻结主进程,以便执行
sleep(1000*1).then(()=>console.log("awake")); console.log("Hello")
it will result in a output它将产生 output
VM2628:1 Hello
VM2628:1 awake
at very end of the sleep.在睡眠的最后。 Of course doing当然在做
setTimeout(()=>sleep(1000*3).then(()=>console.log("awake")),1000);console.log("Hello")
VM2815:1 Hello
undefined
VM2815:1 awake
will make it async, but it does not address my need (to put to sleep
my main process).将使它异步,但它不能满足我的需要(让我的主要进程进入sleep
)。 Any better way?有什么更好的办法吗?
[UPDATE] Promisified version [更新]承诺版本
/**
* Sleep for time [msec]
* @param time int milliseconds
* @return Promise delayed resolve
* @usage
sleep(1000*3).then(()=>console.log("awake"))
*/
sleepP: function (time) {
return new Promise((resolve, reject) => {
var stop = new Date().getTime();
while (new Date().getTime() < stop + time) {
;
}
return resolve(true)
});
}
that can be called like可以这样称呼
await sleepP( 1000 * 3 );
There is no need to freeze at all.根本没有必要冻结。 Because of javascripts asynchronicity we can leave a part of the code for some time and resume later.由于 javascripts 的异步性,我们可以将部分代码保留一段时间,稍后再继续。 At first we need a promising timer:首先我们需要一个有前途的计时器:
const timer = ms => new Promise( res => setTimeout(res, ms));
Then we can simply use it:然后我们可以简单地使用它:
console.log("wait 3 seconds")
timer(3000).then(_=>console.log("done"));
Or with a bit syntactic sugar:或者用一点语法糖:
(async function(){
console.log("wait 3 seconds");
await timer(3000);
console.log("done");
})()
If you really want to freeze ( very bad ), you don't need promises at all:如果你真的想冻结(非常糟糕),你根本不需要承诺:
function freeze(time) {
const stop = new Date().getTime() + time;
while(new Date().getTime() < stop);
}
console.log("freeze 3s");
freeze(3000);
console.log("done");
function sleep(time, func){
if (typeof func === 'function'){
const timer = ms => new Promise( res => setTimeout(res, ms));
timer(time).then(i=>func());
}
else{
console.log('What about the function bro?')
}
}
sleep(1000, function(){
console.log('hello')
console.log('test')
var arr = [1,2,3,4]
arr.forEach(i => console.log(i))
})
Since Node v15.0.0 there's a new way to sleep by using the Timers Promises API .从 Node v15.0.0 开始,有一种使用Timers Promises API的新睡眠方式。
import {setTimeout} from 'timers/promises';
const bucket = ['a', 'b', 'c'];
for(const item of bucket) {
await getItem(item);
await setTimeout(100);
}
If you want to use also use the regular setTimeout
timer you can alias the promise timer.如果您还想使用常规的setTimeout
计时器,您可以给 promise 计时器起别名。
import {setTimeout as sleep} from 'timers/promises';
I have an issue where I'm uploading to a remote database using an asynchronous write and it goes too fast, and I hit a rate limiter.我有一个问题,我正在使用异步写入上传到远程数据库并且速度太快,并且我遇到了速率限制器。
So I need to actually pause between sections of code.所以我实际上需要在代码段之间暂停。
My application isn't in a browser or a server, it's just a command line utility so I'm not concerned about blocking the main execution thread.我的应用程序不在浏览器或服务器中,它只是一个命令行实用程序,所以我不担心阻塞主执行线程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.