Javascript Promise (Examples)
In Javascript promises are used to handle asynchronous operations. It is either resolved or rejected based on the result of the asynchronous operation.
Basic 1
The following example shows how to create a promise and how to resolve it.
let done = true;
new Promise((resolve, reject) => {
if (done) {
resolve("Job done");
} else {
reject("Still working");
}
})
.then(val => {
console.log(val);
})
.catch(val => {
console.log(val);
});
Basic 2
The following example shows how to create a promise in a variable and how to listen to the promise using that variable.
let done = true;
const isJobDone = new Promise((resolve, reject) => {
if (done) {
resolve("Job done");
} else {
reject("Still working");
}
});
isJobDone
.then(val => {
console.log(val);
})
.catch(val => {
console.log(val);
});
Basic 3
The following example shows how to create a promise in a variable and how to listen whenever we want.
let done = true;
const isJobDone = new Promise((resolve, reject) => {
if (done) {
resolve("Job done");
} else {
reject("Still working");
}
});
const check = function() {
isJobDone
.then(val => {
console.log(val);
})
.catch(val => {
console.log(val);
});
};
check();
Chaining 1
This example shows how to chain promises.
let done = true;
new Promise(function(resolve, reject) {
if (done) {
resolve("Job done");
} else {
reject("Still working");
}
})
.then(function(val) {
return val + " - Verified";
})
.then(function(val) {
console.log(val);
})
.catch(val => {
console.log(val);
});
Chaining 2
This example shows how to chain promises by returning a promise.
const check1 = function(response) {
if (response == "Job done") {
return Promise.resolve(response + "- verified");
// or
return response + "- verified";
} else {
return Promise.reject("Verification failed");
// or
return "Verification failed";
}
};
const check2 = function(response) {
console.log(response);
};
let done = true;
new Promise(function(resolve, reject) {
if (done) {
resolve("Job done");
} else {
reject("Still working");
}
})
.then(check1)
.then(check2)
.catch(val => {
console.log(val);
});
