0

I am writing a code in javascript which is using promises. The code is as follows:-

function resolveAfter2Seconds() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve("here");
    }, 15000);
  });
}

async function asyncCall() {

  let a = ""

  const result1 = await resolveAfter2Seconds();
  const result2 = await resolveAfter2Seconds();
  a.concat(result1, result2)
  console.log('calling');
  console.log(a)

}

asyncCall();
console.log("tmkoc")

i am not getting that why the output of a is "" because the code is declared as async await so the function must wait until each call is resolved and then the concatenation happen and then console log must happen.

Andy
  • 61,948
  • 13
  • 68
  • 95

1 Answers1

3

It's not a problem with async/await, it works correctly here.

The problem is that a.concat returns a new string, it does not mutate the original one.

To fix your code you would have to reassign a variable

function resolveAfter2Seconds() {
 return new Promise(resolve => {
  setTimeout(() => {
  resolve("here");
  }, 15000);
   });
 }

async function asyncCall() {

  let a  = ""

  const result1 = await resolveAfter2Seconds();   
  const result2 = await resolveAfter2Seconds();  
  a = a.concat(result1,result2) // reassign the variable
  console.log('calling');
  console.log(a) 

}

asyncCall();
console.log("tmkoc")
Terminat
  • 1,199
  • 5
  • 21