0

I am new to JS and I am writing some simple REST API in Node.js for my application. Somewhere inside the code I want to wait for about 5 seconds.

I am so confused about using of Promise and normal timeout method and call the function somewhere else. as following:

const sleep = (time) => {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve()
            console.log('5 seconds');
        }, time);
    })
}

and then call the function:

sleep(5000)

OR

const sleep = (time) => {
    return new Promise(resolve => {
        setTimeout(() => {
           resolve()
           console.log('5 seconds');
       }, time);
    })
}

and then call the function:

sleep(5000).then(() => console.log('5 seconds passed'))

OR

const sleep = (time) => {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve()
            console.log('5 seconds');
        }, time);
    })
}

async function wait(sleepTime) {
    await sleep(sleepTime)
}

and then call the function:

wait(5000)

Am I doing something wrong? Because in all 3 cases I actually get a waiting time of 5 seconds but since the function returns Promise, I have to use .then() If I want to use the Promise.

Angels
  • 325
  • 4
  • 15
  • Yes, you always need to use `then` or `await` to wait for the delay and defer things like `console.log('5 seconds passed')` after it. There is no difference between your snippets with respect to that. – Bergi Oct 12 '19 at 17:16
  • Btw, you really should remove that `console.log('5 seconds');` line from the `sleep` function that has a parameter for dynamic sleep times. – Bergi Oct 12 '19 at 17:17
  • when you have a function that returns a Promise you have to use it inside another function with 'await' to call it OR you use 'then' . But is it possible not to use both 'await and then' and still get the answer? as it happens in 1st case. – Angels Oct 12 '19 at 17:28
  • What do you mean by "answer", and what does happen "in 1st case"? No, it's fundamentally impossible to get a result from the future immediately, you have to wait one way or another. – Bergi Oct 12 '19 at 17:30
  • in these 3 cases I get the same answer. If they are the same then why I should use '.then' after calling the function? – Angels Oct 12 '19 at 17:32
  • If by "answer" you refer to the log output, the second case should be different as it logs twice. You should use `then` because it allows you to do different things after the promise fulfilled, e.g. `sleep(5000).then(() => console.log('5 sec'))` vs `sleep(3000).then(() => console.log('3 sec'))`. If you are just looking for the advantage of using promises over plain callbacks, see [this answer](https://stackoverflow.com/a/22562045/1048572) – Bergi Oct 12 '19 at 18:07

3 Answers3

0

then you use when you want to get the result of promise, promise's code will work anyway even without using its result

Dmitry Reutov
  • 2,995
  • 1
  • 5
  • 20
0

Update: In case 3, you can await an async function.

(async () => {
  await wait(5000);
  // Do something after 5 sec
})();

There is nothing wrong with your code. So I am not sure what is your problem.

Anyway, you can understand Promise in this way:

new Promise(resolve => {
  setTimeout(() => {
    resolve();
  }, 5000);
}).then(() => {
  // Do something after 5 sec 
});

is equivalent to

setTimeout(() => {
  // Do something after 5 sec
}, 5000);
Harry Chang
  • 379
  • 2
  • 4
0

First case.
1. Asynchronous Execution as doSomething() doesn't wait for sleep function to finish execution.
2. The promise will remain in pending state.

sleep(5000); 
doSomething();// execution starts without waiting for 5 seconds.

Second Case :
1.Promise is resolved the then()/catch() listener is called.
2. Making doSomething() execute after sleep() has finished its execution.

sleep(5000).then(() => {doSomething();// execution starts after waiting for 5 seconds. })

Third Case :
1. Async function returns a promise.
2. Await/then - works in the same way (resolves/rejects a promise and return data/error).
3. Await can only be used inside async function.

I would suggest you create only one async function which contains the business logic for the api.

async function wait(sleepTime) {
    // some code 
    await sleep(sleepTime); // waiting  
    doSomething(); // execution starts only after waiting.
    // some other code
}

Calling wait without then will result in pending promise but that would not affect your business logic.

// sample example.
wait(5000).then(()=>{res.send("ok");}).catch(e=>{res.send("err")});
Mukul Dev
  • 196
  • 8