Search code examples
node.jspromisees6-promise

Return a promise without waiting for a dependant promise in function in nodejs


I am using node 8.x. Hence, I have access to all latest features i.e. async/ await etc.

The scenario is similar to following (Not correct syntax, just for explanation):

createUser()
{
    let userAddress = createAddress(); // Aync, returns a promise
    User.create(name: 'foo', address: userAddress); // User creation is dependant on address. Also, User.create returns a promise.
}

Basically, User object creation is dependant on the creation of address object. I want the createUser function to execute asynchronously i.e. to return a promise as soon as possible without waiting for address object to be created.

The purpose of this question is not to get things done but to understand what is the best way to solve this kind of issues in async programming.

Few ways that I can think of: 1: Create a new promise object and return right away when entered in createUser function. Resolve it when the user object is created. 2: Make createUser an async function and then return user Promise. Facing issues with this method:

async function createUser()
{
    address = await createAddress();
    return User.create(name: 'foo', address: userAddress);
}

The problem is function waits for the address before returning the control which I don't want. (Or it does not make any diff as the function is async. Performance is a big criterion in my case)

How to deal with this kind of promise dependancy where you want to return promise of parent object but you parent object is dependant on child object's promise.

Thank you.


Solution

  • Make createUser an async function and then return user Promise. The problem is function waits for the address before returning the control which I don't want.

    No, it doesn't. An async function does immediately return a promise to its caller. It waits only when executing the code in its body (and resolves the promise when you return). Your code works, this is exactly what you should be doing.