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.

2
  • 1
    asyncCall(); is not called asynchronously, so it won't be awaited. Commented Aug 18, 2022 at 20:25
  • Note: your resolveAfter2Seconds actually resolves after 15 seconds. Commented Aug 18, 2022 at 20:29

1 Answer 1

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")

Sign up to request clarification or add additional context in comments.

2 Comments

thanks for answering , i made a silly mistake there
Don't worry, it happens, sometimes it's not visible at the first look :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.