let promise = new Promise(resolve => {
setTimeout(() => resolve("done!"), 1000);
});
promise.then(alert); // shows "done!" after 1 second
// in the above snippets ,how alert is taking the value "done" as we are not passing any arguments inside alert
For promise there are two things that can be returned Accept
(success) Reject
(failure). Normally we do something like this to achieve the promise response, as you can see here we are taking 2 temporary variables to alert, if success then result variable will be alert and if failed then error variable will be alert.
let promise = new Promise(function(resolve, reject) {
setTimeout(() => reject(new Error("Whoops!")), 1000);
});
// reject runs the second function in .then
promise.then(
result => alert(result), // doesn't run
error => alert(error) // shows "Error: Whoops!" after 1 second
);
Incase of you only insterested in succesfully completion then you can use this.
let promise = new Promise(resolve => {
setTimeout(() => resolve("done!"), 1000);
});
promise.then(alert); // shows "done!" after 1 second
What it does? It will actually get result as "done" and as you already have applied alert the "done" will be passed to alert like this alert("done")
.
To catch directly you can use this:
let promise = new Promise((resolve,reject) => {
setTimeout(() => reject("failed!"), 1000);
});
promise.catch(alert); // shows "failed!" after 1 second