6

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.

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

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

}

3 Answers 3

6

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.

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.

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

Sign up to request clarification or add additional context in comments.

Comments

2

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.

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

8 Comments

thanks. 1. in case I cannot use async to the main , I can only use promise all ? with promise.all It will not wait to both function to finish and then process to getServices etc ?
@JennyM (1) You should be able to make main() async. What makes you think you can't? Just make sure you handle any rejections. (2) The promise returned by Promise.all becomes fulfilled when all promises passed in are fulfilled. The very act of calling GetServices() and GetProcess() is what starts those operations; Promise.all only awaits the returned promises. It's not capable of actually starting any async operations itself. Therefore, the async operations will all proceed concurrently.
ok let me try it :) , btw which way is preferred(or you would use), the first or the second ?
@JennyM That depends on what //Here additional code is running actually is, which I can't see in your question.
@cdhowie - please see my edit, I want to run the functions in background and start generator prompt and later on from the prompt access to the result of the prompts, I put some minimal example which ilustrate the point
|
2

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. 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.

 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... 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.