0

I'm playing with async/await and with the code below, shouldn't response be empty or null until the setTimeout in the response const has finished after 5 seconds? and shouldn't response return xyz instead of 1?

async function test() {
  try {
    const response = await setTimeout(
      function() { 
        const obj = {};
        obj.text = "xyz";
        console.log('should console log after 5 seconds')
        return obj;
      }, 
    5000)

    if (response) {
      console.log(`response is ${response}`)
      console.log(`response.text is ${response.text}`)
    }
  } 
  catch(err) {
    console.log(err)
  }
}

test();

2 Answers 2

1

You have to put a Promise to await the setTimeout().

async function test() {
try {
    const response = await new Promise((resolve) => {
        setTimeout(
            function() {
                const obj = {};
                obj.text = "xyz";
                console.log('should console log after 5 seconds')
                return resolve(obj);
            },
            5000)
    });

    if (response) {
        console.log(`response is ${response}`)
        console.log(`response.text is ${response.text}`)
    }
}
catch(err) {
    console.log(err)
}
}

test();

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

2 Comments

I thought the whole point of async was something cleaner to use than promise?
The await operator is used to wait for a Promise. You have to use the await in an async function.
1

For your code to work as per the expectations, you need to wrap the set timeout in a promise. Check the snippet. Without wrapping it in promise, setTimeout returns value immediately which is the ID value of the timer.

async function test() {
  try {
    const response = await new Promise(function(resolve, reject) {
      setTimeout(
        function() {
          const obj = {};
          obj.text = "xyz";
          console.log('should console log after 5 seconds')
          resolve(obj);
        },
        5000)
    })

    if (response) {
      console.log(`response is ${response}`)
      console.log(`response.text is ${response.text}`)
    }
  } catch (err) {
    console.log(err)
  }
}

test();

4 Comments

I thought the whole point of async was something cleaner to use than promise?
Yes but setTimeout does not return a promise. It returns the ID value of the timer. Check w3schools.com/jsref/met_win_settimeout.asp
how can I tell what would or wouldn't return a promise of its own?
Console log the return value. If its a promise, it will print promise. Alternatively, check if the return value has a then property. If it does, its a promise

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.