2

I am trying to use the array destructing assignment to get the results from Promise.all(). Here is my code:

const[_, resFunc2] = await Promise.all([
      func1(),
      func2(),
    ]);

func1 doesn't return any value, and func2 returns a value which will be assigned to resFunc2. I want to ask what's the best practice for handling the result of func1 since func1 doesn't return any value? Thanks a lot~

7
  • Do you mean that func1 returns a promise that resolve in null? Commented May 16, 2019 at 21:06
  • Have you tried using Array#filter to remove undefined values? .filter(x => x !== undefined) Commented May 16, 2019 at 21:08
  • 1
    Reverse the order of the promises and then deconstruct to just one array value. Ignoring the second value as it will be discarded. Commented May 16, 2019 at 21:11
  • @cgTag, this is a good solution Commented May 16, 2019 at 21:15
  • @Federkun, yes. Commented May 16, 2019 at 21:16

2 Answers 2

2

Have you considered the simplest possibility?

const resFunc2 = (await Promise.all([
      func1(),
      func2(),
    ]))[1];

If you are insistent on destructuring (I have to admit, it's super-cool), you could do this.

const [resFunc2] = await Promise.all([
      func2(),
      func1(),
]);
Sign up to request clarification or add additional context in comments.

Comments

2

There are a variety of possibilities, depending on what you need to do with the result.

You can use default values if you need a specific value.

const [_ = 0, resFunc2] = await Promise.all([
      func1(),
      func2(),
]);

You can omit it if you don't need it at all

const [, resFunc2] = await Promise.all([
      func1(),
      func2(),
]);

Disclaimer: I didn't test any of these

3 Comments

I really like your second solution. I didn't know that was even allowed. Almost as good as mine :-). I didn't know about the first possibility either, but I don't think it fits the need. The third one can go wrong too many ways.
Thank you :) - I agree with you on all points! - I like the second one because it expresses its intent quite readable. - number three doesn't make much sense, i'll better remove it, thanks for the feedback.
I came up with a (fourth? fifth?) solution! Still enamored of the empty-comma syntax though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.