How to create a Javascript promise
A promise is a function that will complete a task, usually asynchronously, in the future. A promise is always in one of three states:
pending: initial state, neither resolved or rejected
fulfilled: operation was completed successfully
rejected: operation has failed
to create a promise you use the following syntax:
const myPromise = new Promise((resolve, reject) => {
})
How to complete a promise
To actually complete a promise you must add conditions in the function. Using the previous example this is how you would complete the promise:
const myPromise = new Promise((resolve, reject) => {
if(condition){
resolve("Promise has been fulfilled")
} else {
reject("Promise was rejected")
}
})
Handle a fulfilled promise with then
Often promises are used with server requests since they can take an unknown amount of time. After you fulfill a promise you usually want to do something with the response from the server. To do this you can use the then method. The then method is executed immediately are the promise is resolved. Here is an example:
myPromise.then(result => {
// Write what you will do with result here
console.log(result)
})
Handle a rejected promise with catch
Catch is used when your promise has been rejected. It will be executed immediately after a the reject method is called.
Here is the syntax:
myPromise.catch(error => {
// Write what you will do with error here
console.log(error)
})
Top comments (0)