Search code examples
javascriptasynchronouspromiseasync-awaites6-promise

retuning a promise using async await pattern with some delay


I am trying to return some test data from a method that calls a rest api. To simulate the rest api call, I am adding some delay to return a promise using async-await pattern, but its not working as expected.

My understanding of async-await pattern in JavaScript is that any value returned from an async function is returned as a promise, so the value 100 should be returned as a promise by the function and therefore the last statement using .then should show 100, but it's not.

Question What is wrong with the code snippet below which is causing the alert in last line of code to show undefined rather than 100?

async function f() {

  function delayedResponse() {
    setTimeout(function() { return 100}, 5000);
  }
  return await delayedResponse();

}

f().then(alert); // 100


Solution

  • You don't return anything in your delayedResponse so it's resulted in undefined.

    Instead, in order to achieve what you expect - you can create a promise explicitly and resolve a value using timeout;

    async function f() {
      return new Promise(resolve => {
        setTimeout(function() { resolve(100)}, 5000);
      }); 
    }
    
    f().then(alert); // 100