This blog represents concepts on Promise concept in Javascript with diagrams and code examples. Following is described later in the blog:
- Promise explained with simple example
- Promise execution timeline
- Promise program code sample
Promise Explained with Simple Example
- Lets say, a consumer program invoked an API and asked for the output. In synchronous world, the value is returned then and there and the caller program waits for the service provider program to respond. The execution of the program halts.
- Welcome Promise on board! With Promise concept, the service provider program can respond with a “promise” that it would return output value or error in near future and the caller program continues with the execution. This happens in below program as step 1, 2, 3
- In the meantime, the provider program executes and once the output is evaluated, the program choose to fulfill promise by invoking “resolve” or “reject”. Once the provider program invokes the method, resolve or reject, the output is returned to called program. The caller program consumes the output. This is represented in below program with step 4 and 5.
Promise Execution Timeline
The diagram below represents following:
- The caller program invokes API and gets a Promise in return that the output will be returned in future.
- The caller and the provider program then continues to execute on its timeline.
- Once provider program evaluated the output, it invokes resolve or reject appropriately thereby returning either the value or error respectively.
Promise Program Code Sample
var p = new Promise(function (resolve, reject) {
//
// The program evaluates
//
// Invokes resolve(someObject) based on success criteria
//
// Invokes reject(error) for Error
//
});
Following diagram depicts the code sample:
Latest posts by Ajitesh Kumar (see all)
- Agentic Reasoning Design Patterns in AI: Examples - October 18, 2024
- LLMs for Adaptive Learning & Personalized Education - October 8, 2024
- Sparse Mixture of Experts (MoE) Models: Examples - October 6, 2024
I found it very helpful. However the differences are not too understandable for me