[英]Nodejs running function on background
I've nodes program which I need to run two function in the beginning of the program And later on access the function results, currently with await each function at a time this works, However in order to save a time and not waiting to GetService
and GetProcess
as I need the data later on in the project It takes about 4 seconds to get this data and I want to run it on the background as I don't need the results immediately, How I can do it in node js, If I run promise.all
It would wait until the getService
and getProcess
and then go to rest of the program.我有节点程序,我需要在程序开始时运行两个 function 稍后访问 function 结果,目前等待每个GetService
GetProcess
因为我稍后在项目中需要数据 获取这些数据大约需要 4 秒,我想在后台运行它,因为我不需要立即得到结果,我如何在节点 js 中做到这一点,如果我运行promise.all
它会等到getService
和getProcess
然后 go 到 rest 程序。
an example一个例子
function main() {
//I want to run this both function in background to save time
let service = await GetServices();
this.process = await GetProcess();
…..//Here additional code is running
//let say that after 30 second this code is called
Let users = GetUser(service);
Let users = GetAdress(this.process);
}
im actually running yeoman generator https://yeoman.io/authoring/ https://yeoman.io/authoring/user-interactions.html我实际上正在运行 yeoman 生成器https://yeoman.io/authoring/ https://yeoman.io/authoring/user-interactions.ZFC35FDC70D5FC69D269883A822C7A53
export default class myGenerator extends Generator {
//here I want run those function in background to save time as the prompt to the user takes some time (lets say user have many questions...)
async initializing() {
let service = await GetServices();
this.process = await GetProcess();
}
async prompting() {
const answers = await this.prompt([
{
type: "input",
name: "name",
message: "Your project name",
default: this.appname // Default to current folder name
},
{
type: "confirm",
name: "list",
choises: this.process //here I need to data from the function running in background
}
]);
} }
Let's assume that getServices()
may take 3 seconds and getProcess()
may take 4 seconds, so if you run these both functions at the same time you will be returned in total 4 seconds with the return values from both promises.假设getServices()
可能需要 3 秒,而getProcess()
可能需要 4 秒,因此如果您同时运行这两个函数,您将在总共 4 秒内返回两个 Promise 的返回值。
You can execute the code while this process is running in the background there will be a callback when the promises resolved, your late functions will be called at this stage.您可以在此进程在后台运行时执行代码,当 Promise 解决时将有一个回调,您的后期函数将在此阶段被调用。
Check the below simple example;检查下面的简单示例;
let service; let process; function main() { // Both functions will execute in background Promise.all([getServices(), getProcess()]).then((val) => { service = val[0]; process = val[1]; console.log(service, process); // Aafter completed this code will be called // let users = GetUser(service); // let users = GetAdress(process); console.log('I am called after all promises completed.') }); // Current example. // let service = await GetServices(); // this.process = await GetProcess(); /* Code blocks.. */ console.log('Code will execute without delay...') } function getServices() { return new Promise((resolve, reject) => { setTimeout(() => { resolve("service is returned") }, 3000); }); } function getProcess() { return new Promise((resolve, reject) => { setTimeout(() => { resolve("process is returned") }, 4000); }); } main();
You can start the asynchronous operation but not await it yet:您可以启动异步操作,但还不能等待它:
function suppressUnhandledRejections(p) {
p.catch(() => {});
return p;
}
async function main() {
// We have to suppress unhandled rejections on these promises. If they become
// rejected before we await them later, we'd get a warning otherwise.
const servicePromise = suppressUnhandledRejections(GetServices());
this.processPromise = suppressUnhandledRejections(GetProcess());
// Do other stuff
const service = await servicePromise;
const process = await this.processPromise;
}
Also consider using Promise.all()
which returns a promise for the completion of all promises passed to it.还可以考虑使用Promise.all()
返回一个 promise 来完成传递给它的所有承诺。
async function main() {
const [ services, process, somethingElse ] = await Promise.all([
GetServices(),
GetProcess(),
SomeOtherAsyncOperation(),
]);
// Use the results.
}
To do what who you need, you have to understand the event loop .要做你需要的人,你必须了解事件循环。
Nodejs is designed to work in a single thread unlike languages like go, however nodejs handle proccess on different threads.与 go 等语言不同,Nodejs 设计为在单线程中工作,但是 nodejs 在不同线程上处理进程。 so you can use nextTick () to add a new event to the main thread and it will be executed at the end of the whole block.所以你可以使用 nextTick() 向主线程添加一个新事件,它将在整个块的末尾执行。
function main() {
//I want to run this both function in background to save time
let service = await GetServices();
this.process = await GetProcess();
…..//Here additional code is running
//Let say that after 30 second this code is called
Let users = GetUser(service);
Let users = GetAdr(this.process);
}
function someFunction(){
// do something...
}
main();
process.nextTick(someFunction());// happens after all main () processes are terminated...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.