Search code examples
javascriptasynchronousasync-awaites6-promise

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


Solution

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