Mark
Mark

Reputation: 3272

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

Upvotes: 19

Views: 22847

Answers (1)

Suren Srapyan
Suren Srapyan

Reputation: 68635

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

Upvotes: 33

Related Questions