Search code examples
javascriptnode.jsasync-awaitecmascript-2017

NodeJs - Async/Await inside controller


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


Solution

  • try:

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