Sunday, August 01, 2021

Javascript Promises

Javascript Promises are useful when you have some asychronous operation (e.g. talking to a backend server, waiting for some time interval to expire, etc...), and you want to structure your code a little nicer than a bunch of nested callback functions.

Note that nested callback functions can usually achieve the functionality you need, but you can end up with deeply nested functions and what is often referred to as "callback hell". Promises let you structure the code without all the nested callbacks.

You create a Promise by invoking the Promise constructor: new Promise(). You pass one parameter to the Promise constructor: A callback function where you will implement your asynchronous operation.

The most important detail about the callback function is that it will be called with two parameters: resolve and reject. These parameters are references to functions provided by the Promise. You will call resolve() when your async operation is complete, or reject() if your operation fails. Note that when you call resolve(), you pass it the results of your operation (e.g. the results returned from the server).

That's all there is to setting up your async operation. Now you need to process the results. For this you use the "then" method of the Promise.

let myPromise = new Promise( (resolve, reject) => { 
    setTimeout(()=>resolve('my results'),1000) 

myPromise.then(result => console.log(result));

In the above code, myPromise is created with an async operation that will take 1 second to complete. myPromise.then() is called to register a callback function to run when the promise has resolved. Note that then() is called right away, while the async operation is ongoing. After one second, the promise resolves and the callback registered with then() will run and console.log the result.

There are a few more details to understand about Promises, but the example I've given shows the main underlying idea. Your async operation runs and let's the promise know when it's done, or when it's failed, and the Promise object takes care of informing any code that has registered interest in the result by calling then().

In a later post I'll talk about what happens when you call then() multiple times, and also how to handle an array of multiple promises to deal with a set of parallel async operations.

Image Credit: Alex Blajan, CC-BY-SA 2.0

Post a Comment

Note: Only a member of this blog may post a comment.