Nodejs在后台运行功能

问题描述 投票:1回答:1

我有一个节点程序,我需要在程序开始时运行两个函数,然后再访问函数的结果,目前用 await 每个函数一次就可以了,但是为了节省时间,不需要等待。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.ioauthoringhttps:/yeoman.ioauthoringuser-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
      }
    ]);

}

javascript node.js multithreading async-await
1个回答
1
投票

你可以开始异步操作,但还没有 await。

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

也可以考虑使用 Promise.all() 其中返回一个承诺,用于完成所有传递给它的承诺。

async function main() {
  const [ services, process, somethingElse ] = await Promise.all([
    GetServices(),
    GetProcess(),
    SomeOtherAsyncOperation(),
  ]);

  // Use the results.
}

1
投票

要做你需要的事,你必须了解 事件循环.

Nodejs与go等语言不同,它被设计为在一个线程中工作,然而nodejs在不同的线程上处理进程,所以你可以使用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...

1
投票

我们假设 getServices() 可能需要3秒和 getProcess() 可能需要4秒,所以如果你同时运行这两个函数,你将在4秒内得到两个承诺的返回值。

你可以在这个进程在后台运行时执行代码,当承诺解决时,会有一个回调,你的后期函数将在这个阶段被调用。

请看下面的简单例子。

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();
© www.soinside.com 2019 - 2024. All rights reserved.