javascript await in the caller and in the callee

Viewed 40

I have a service class called: Test

That Test Class has a function called: getMe()

In that getMe function, I have 3 await statements, 2nd needs the answer from the first one, third one needs an answer from the second one. An example:

class Test {
   async getMe() {
      const res1 = await promise1;
      const res2 = await promise2(res1);
      const res3 = await promise3(res2);
      return res3;
   }
}

Now, somewhere in my code, i call this function.

const a = new Test();
try{
  const res = await a.getMe();
}catch(err){
  console.log("error", err);
}

Now, because of the fact that in getMe function, I already await promises, It's not optimized since there's a middle promise created. Read this: Difference between `return await promise` and `return promise`

So, I am wondering, If in the getMe function, I shouldn't write await for optimizations and return promise directly, how could my code be written ? I don't want in my outside code to call await promise1, promise2, promise3 because then I'd not have a single function which takes care of the final bits and my code would be scattered.

What do you think and could be your advice ?

2 Answers

Since the promises inside getMe() are dependent on each other (e.g. promise2 requires the resolved value of promise1 as an input-parameter), you cannot really optimize something here (apart from directly returning the last promise).

If they weren't dependent on other you could certainly use Promise.all() in order to process them non-sequentially, return its promise and just await this promise in the calling function.

The only thing you could do to optimize it, would be to return the result of promise3 directly.

class Test {
   async getMe() {
      const res1 = await promise1;
      const res2 = await promise2(res1);
      return promise3(res2);
   }
}

Other than that, I dont see any way, as the three functions are dependent on one another.

Related