-1

I have a simple yet perplexing issue with async functions. I wish to simply return the value when its ready from the function.

Here is a sample code:

async function test() {
  setTimeout(function() {
    return 'eeeee';
  }, 5000);
}

test().then(x => {
  console.log(x)
});
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64

3 Answers3

1

You will get undefined been logged at once.

It's clear that you are trying to write a sleep() async function, but do remember that setTimeout is a sync function calling with a callback function will be executed at a given time, so while you are executing test(), the calling will run to end and return undefined as you have no return statement in the function body, which will be passed to your .then() function.

The right way to do this is to return a Promise that will be resolved after a given time, that will continue the then call.

async function sleep(time){
  return new Promise((resolve,reject) => {
    setTimeout(() => {
      resolve("echo str")
    },time)
  })
}

sleep(5000).then((echo) => console.log(echo))

sleep function in short

const sleep = async time => new Promise(resolve=>setTimout(resolve,time))
Oboo Cheng
  • 4,250
  • 3
  • 24
  • 29
  • For those of you who are confused with the `return Promise` and `return await Promise`:[Difference between return await promise and return promise](https://stackoverflow.com/questions/38708550/difference-between-return-await-promise-and-return-promise#:~:text=Most%20of%20the%20time%2C%20there,between%20return%20and%20return%20await%20.&text=The%20second%20version%20of%20the,caller%20gets%20the%20rejection%20instead.) – Oboo Cheng Jun 21 '20 at 07:07
0

An async function has to return a promise. So to fix this, you can wrap your setTimeout function in a new promise like so:

async function test(){
  return await new Promise((resolve, reject) => {
      setTimeout(function(){
          resolve('eeeee');
      },5000);
  })
}

test().then(x => {
  console.log(x)
});

You can learn more about async/await on the MDN docs here. Hope this helps!

itsanewabstract
  • 1,006
  • 3
  • 12
0

With Promises

const setTimer = (duration) => {
      const promise = new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve('Done!');
        }, duration);
      });
      return promise;
    };
    
    setTimer(2000).then((res) => console.log(res));
herosuper
  • 164
  • 1
  • 9