1

I have this simple example to my controller and doesn't work as expected

export let create = async (req: Request, res: Response) => {

   console.log("START");
   await setTimeout(() => {
      console.log("MIDDLE");
   }, 1000);
   console.log("END");
   return res.json({ data: null });

};

Output: START,END,MIDDLE

EXPECT: START,MIDDLE,END

Michalis
  • 6,247
  • 11
  • 47
  • 71

2 Answers2

2

try:

await new Promise(resolve => setTimeout(resolve, 1000))

Lev Kuznetsov
  • 3,235
  • 4
  • 18
  • 33
0

You're using setTimeOut without creating the promise object, so it's waiting for the setTimeOut value to be returned (which is instant) rather than waiting for a promise resolution. This is the reason your await statement isn't working the way it was intended to. What you need is to create a promise:

function resolveAfterOneSecond(x) { 
  return new Promise(resolve => {
    setTimeout(() => {
      console.log("Middle");
      resolve(x);
    }, 1000);
  });
}

async function f1() {
  var x = await resolveAfterOneSecond(10);
  console.log("End");
}

console.log("Begin");
f1();

and then set your function to await the return of the promise, rather than the return of the setTimeOut function integer.

Peter David Carter
  • 2,338
  • 8
  • 24
  • 43