Home > Software engineering >  What is difference between Promise, await/async, and setTimeout?
What is difference between Promise, await/async, and setTimeout?

Time:04-14

I understood the difference between Promise and await/asyc is error handling and readable code. Promise can use .catch() for error handling, but async/await doesn't have a function to error handle, so we have to use try-catch(), and async/await is better when code becomes longer.

But I couldn't get the difference between setTimeout. What is the difference between three asynchronous functions?

Thanks a lot for any help :)

CodePudding user response:

With setTimeout you just set a time in milliseconds that the procedure should wait until the callback function inside the setTimeout call is getting called.

Meaning:

setTimeout(() => {
   console.log('Hello World!');
}, 1000);

When the setTimeout is getting executed, it will wait 1000 milliseconds = 1 second until it performs the console.log(); action.

In case of error handling, you still need to handle your errors manually, but you're also able to resolve Promises in the setTimeout. So you could tell the program that it should wait 1 second until it resolves the Promise and it can catch exceptions as you said with the .catch() on the Promise call.

TL;DR: Async methods just wait until the method is done (if you await them) and setTimeout executes a code block after a given amount of milliseconds.

  • Related