Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript promise resolving with setTimeout

I don't understand why the first setTimeout function works but the second one doesn't. The first one is commented out when I run the second setTimeout. But instead of resolving after 3 seconds it resolves immediately.

I'm new to the whole 'promise' thing and the tutorial I'm working through uses promises with setTimeout a lot.

  let promise = new Promise( ( resolve, reject ) => {

     /* why does setTimeout work with this one... */
     setTimeout( () => resolve( 'Job\'s done!!!' ), 3000 );

     /* but not with this one */
     setTimeout( resolve('done'), 3000 );
  } );

  promise.then(
     result => alert( result )
  );
like image 206
Ivan Avatar asked Oct 03 '17 19:10

Ivan


People also ask

Does setTimeout return promise?

We can wrap setTimeout in a promise by using the then() method to return a Promise. The then() method takes upto two arguments that are callback functions for the success and failure conditions of the Promise. This function returns a promise.

Which will run first promise or setTimeout?

Promise is getting resolved as soon as it is created whereas setTimeout comes later in the queue..

How do you write a setTimeout in promise?

setTimeout() is not exactly a perfect tool for the job, but it's easy enough to wrap it into a promise: const awaitTimeout = delay => new Promise(resolve => setTimeout(resolve, delay)); awaitTimeout(300). then(() => console.

How do you wait for a promise to resolve?

You can use the async/await syntax or call the . then() method on a promise to wait for it to resolve. Inside of functions marked with the async keyword, you can use await to wait for the promises to resolve before continuing to the next line of the function.


1 Answers

/* why does setTimeout work with this one... */
 setTimeout( () => resolve( 'Job\'s done!!!' ), 3000 );

when the timeout occur you call a function () => ... wich when executed till resolve the promise

/* but not with this one */
 setTimeout( resolve('done'), 3000 );

here you actually resolve the promise (you execute the result function) and pass the result to the setTimeout function.

Writing

() => resolve( 'Job\'s done!!!' )

is the same as

function() {
    resolve( 'Job\'s done!!!' );
}
like image 161
Peter Avatar answered Sep 30 '22 04:09

Peter