gpt4 book ai didi

javascript - Nodejs后台运行函数

转载 作者:行者123 更新时间:2023-12-01 15:39:58 25 4
gpt4 key购买 nike

我有 Node 程序,我需要在程序开头运行两个函数稍后访问函数结果,目前每次等待每个函数都有效,但是为了节省时间而不是等待 GetServiceGetProcess 因为我稍后需要在项目中获取数据获取此数据大约需要 4 秒,我想在后台运行它,因为我不需要立即获得结果,我如何在 Node js 中做到这一点,如果我运行 promise.all 它会等到 getServicegetProcess 然后去休息程序。

一个例子

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);
}

我实际上正在运行 yeoman 生成器 https://yeoman.io/authoring/ https://yeoman.io/authoring/user-interactions.html

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
}
]);

}

最佳答案

假设 getServices() 可能需要 3 秒,getProcess() 可能需要 4 秒,所以如果您同时运行这两个函数,您将两个 promise 的返回值总共返回 4 秒。

当这个进程在后台运行时,您可以执行代码,当 promise 解决时会有回调,您的延迟函数将在这个阶段被调用。

检查下面的简单示例;

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();

关于javascript - Nodejs后台运行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61374421/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com