首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在不影响其他线程的情况下休眠node.js中的线程?

如何在不影响其他线程的情况下休眠node.js中的线程?
EN

Stack Overflow用户
提问于 2012-11-19 13:50:55
回答 2查看 128.7K关注 0票数 80

根据Understanding the node.js event loop,node.js支持单线程模型。这意味着如果我向node.js服务器发出多个请求,它不会为每个请求产生新的线程,而是逐个执行每个请求。这意味着如果我在node.js代码中对第一个请求执行了以下操作,同时节点上出现了一个新请求,则第二个请求必须等待第一个请求完成,包括5秒睡眠时间。对吗?

代码语言:javascript
复制
var sleep = require('sleep');
    sleep.sleep(5)//sleep for 5 seconds

有没有办法让node.js为每个请求派生一个新的线程,这样第二个请求就不必等待第一个请求完成,或者我可以只在特定的线程上调用睡眠?

EN

回答 2

Stack Overflow用户

发布于 2017-04-28 23:45:36

如果你有一个包含异步请求的循环,并且你希望每个请求之间有一定的时间间隔,你可以使用下面的代码:

代码语言:javascript
复制
   var startTimeout = function(timeout, i){
        setTimeout(function() {
            myAsyncFunc(i).then(function(data){
                console.log(data);
            })
        }, timeout);
   }

   var myFunc = function(){
        timeout = 0;
        i = 0;
        while(i < 10){
            // By calling a function, the i-value is going to be 1.. 10 and not always 10
            startTimeout(timeout, i);
            // Increase timeout by 1 sec after each call
            timeout += 1000;
            i++;
        }
    }

此示例在每个请求后等待1秒,然后发送下一个请求。

票数 1
EN

Stack Overflow用户

发布于 2020-05-27 02:40:01

在使用第三方库提供的异步函数或观察值时,例如Cloud firestore,我已经找到了如下所示的waitFor方法的函数(TypeScript,但您明白了……)当你需要等待某个进程完成,但又不想在回调中嵌入回调,也不想冒着无限循环的风险时,这是很有帮助的。

这种方法有点类似于while (!condition)休眠循环,但会以异步方式产生,并定期对完成条件执行测试,直到为真或超时。

代码语言:javascript
复制
export const sleep = (ms: number) => {
    return new Promise(resolve => setTimeout(resolve, ms))
}
/**
 * Wait until the condition tested in a function returns true, or until 
 * a timeout is exceeded.
 * @param interval The frenequency with which the boolean function contained in condition is called.
 * @param timeout  The maximum time to allow for booleanFunction to return true
 * @param booleanFunction:  A completion function to evaluate after each interval. waitFor will return true as soon as the completion function returns true.   
 */
export const waitFor = async function (interval: number, timeout: number,
    booleanFunction: Function): Promise<boolean> {
    let elapsed = 1;
    if (booleanFunction()) return true;
    while (elapsed < timeout) {
        elapsed += interval;
        await sleep(interval);
        if (booleanFunction()) {
            return true;
        }
    }
    return false;
}

说你在后端有一个长时间运行的进程,你想在承担其他任务之前完成。例如,如果你有一个汇总账户列表的函数,但你想在计算之前从后台刷新账户,你可以这样做:

代码语言:javascript
复制
async recalcAccountTotals() : number {
     this.accountService.refresh();   //start the async process.
     if (this.accounts.dirty) {
           let updateResult = await waitFor(100,2000,()=> {return !(this.accounts.dirty)})
     }
 if(!updateResult) { 
      console.error("Account refresh timed out, recalc aborted");
      return NaN;
    }
 return ... //calculate the account total. 
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13448374

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档