-2

I have very simple case scenarios, where I need to wait for few seconds before doing further execution.

I tried to set timeout function separately, exporting module or function only. nothing seems to work.

module.exports.tests = async () => {
console.log("inside test function")
await new Promise(async (resolve: any) => {
    setTimeout(resolve, 5000);
  });

// Do actual work
console.log("Starting actual work");

}

When I call this function

./node_modules/.bin/ts-node -e 'require(\"./src/tests.ts\").tests()

I would expect this to print "Starting actual work", But it never reaches there. It is printing "inside test function" and returning before calling actual work. What possibly I'm doing wrong here?

Jeremy
  • 1
  • 85
  • 340
  • 366
ZAM
  • 47
  • 1
  • 4
  • 1
    Using plain node it's seem to be working. – adambene May 15 '19 at 14:43
  • Also works with ts-node without any problems. Do you get any other errors? Can you also try to drop the `.ts` at the end of your `"./src/tests.ts"`.. Additionally you might not need to escape the quotes here (which also could cause errors) – lumio May 15 '19 at 14:46
  • 1
    Tried did not work. Agree with you it work plain node. `public async test(event: any) { console.log('Before'); await new Promise(async (resolve: any) => { setTimeout(resolve, 5000); }); console.log('After');` – ZAM May 15 '19 at 14:56
  • That's why I am clueless why it is not working in above case ? Promise always find a way to make you feel stupid. – ZAM May 15 '19 at 14:58
  • @Jeremy, No error. It seems all normal printing first statement and exist function. – ZAM May 15 '19 at 15:00
  • Hmm. [It works on my machine](https://i.stack.imgur.com/XptQF.png). – Jeremy May 15 '19 at 15:02

1 Answers1

-2

The await is what block you.

await/async are used to more easily handle promises.

What you are telling the language is:

- print "inside test function"
- wait for this promise to resolve and return me the value it returns
- print "Starting actual work"

but since your promise resolves in 5 seconds, it won't print the second string if not after 5 seconds.

The example would work are expected if your write this:

module.exports.tests = async () => {
    console.log("inside test function")
    (new Promise((resolve: any) => {
        setTimeout(resolve, 5000);
     })).then(() => console.log("printed after 5 seconds"));
    // Do actual work
    console.log("Starting actual work");
}

Here a fiddle to see how it works.

bracco23
  • 2,181
  • 10
  • 28
  • This is not an answer for what OP was asking. – lumio May 15 '19 at 14:47
  • Yes this is not answer I am looking for. Without await it will work but I need to wait for certain time before doing actual work. – ZAM May 15 '19 at 14:50