Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return multiple variables on async/await

I was wondering if there is a way to get the second resolve value (test2) without returning arrays or JavaScript objects.

function testFunction() {
  return new Promise(function(resolve, reject) {
    resolve("test1", "test2");
  });
}

async function run() {
  var response = await testFunction();
  console.log(response); // test1
}

run();
like image 875
Mark Avatar asked Sep 07 '17 07:09

Mark


1 Answers

You can pass only one item. But starting from ES6 there is a good feature called Array Destructuring.

Return an array and you can leave the properties assignment under the hood.

function testFunction() {
    return new Promise(function(resolve, reject) {
  	       resolve([ "test1", "test2"] );
           });
}

async function run() {

  const [firstRes, secondRes] = await testFunction();
  
  console.log(firstRes, secondRes);

}

run();
like image 70
Suren Srapyan Avatar answered Sep 19 '22 11:09

Suren Srapyan