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

3
  • 1
    And what do you expect? Commented Dec 27, 2017 at 14:29
  • I think it is obvious.... START... MIDDLE... END Commented Dec 27, 2017 at 14:30
  • 1
    setTimeout returns a number, not a promise. Only if you await a promise does the execution actually "wait". Commented Dec 27, 2017 at 14:31

2 Answers 2

2

try:

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

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

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.