根据Understanding the node.js event loop,node.js支持单线程模型。这意味着如果我向node.js服务器发出多个请求,它不会为每个请求产生新的线程,而是逐个执行每个请求。这意味着如果我在node.js代码中对第一个请求执行了以下操作,同时节点上出现了一个新请求,则第二个请求必须等待第一个请求完成,包括5秒睡眠时间。对吗?
var sleep = require('sleep');
sleep.sleep(5)//sleep for 5 seconds
有没有办法让node.js为每个请求派生一个新的线程,这样第二个请求就不必等待第一个请求完成,或者我可以只在特定的线程上调用睡眠?
发布于 2017-04-28 23:45:36
如果你有一个包含异步请求的循环,并且你希望每个请求之间有一定的时间间隔,你可以使用下面的代码:
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秒,然后发送下一个请求。
发布于 2020-05-27 02:40:01
在使用第三方库提供的异步函数或观察值时,例如Cloud firestore,我已经找到了如下所示的waitFor
方法的函数(TypeScript,但您明白了……)当你需要等待某个进程完成,但又不想在回调中嵌入回调,也不想冒着无限循环的风险时,这是很有帮助的。
这种方法有点类似于while (!condition)
休眠循环,但会以异步方式产生,并定期对完成条件执行测试,直到为真或超时。
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;
}
说你在后端有一个长时间运行的进程,你想在承担其他任务之前完成。例如,如果你有一个汇总账户列表的函数,但你想在计算之前从后台刷新账户,你可以这样做:
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.
}
https://stackoverflow.com/questions/13448374
复制相似问题