2023-10-05 12:20:00 +02:00
|
|
|
// https://javascript.info/promise-basics
|
|
|
|
|
|
|
|
/*
|
|
|
|
The function passed to Promise is called "executor". When Promise gets
|
|
|
|
created, the executor gets executed.
|
|
|
|
When the Promise ends, it should either call the "resolve" or "reject"
|
|
|
|
callbacks:
|
|
|
|
resolve(value) — if the job is finished successfully, with result value.
|
|
|
|
reject(error) — if an error has occurred, error is the error object.
|
2024-02-15 16:23:47 +01:00
|
|
|
|
|
|
|
Remember that Promises are not intrensically asyncronous
|
2023-10-05 12:20:00 +02:00
|
|
|
*/
|
2024-02-23 11:17:02 +01:00
|
|
|
const promise = new Promise(function (resolve, reject) {
|
|
|
|
setTimeout(() => resolve('done'), 500);
|
|
|
|
});
|
2023-10-05 12:20:00 +02:00
|
|
|
|
|
|
|
/*
|
|
|
|
The first argument of .then is a function that runs when the promise is resolved and receives the result.
|
|
|
|
The second argument of .then is a function that runs when the promise is rejected and receives the error.
|
|
|
|
*/
|
|
|
|
promise.then(
|
2024-02-23 11:17:02 +01:00
|
|
|
result => console.log('The operation was successful. It returned ' + result),
|
|
|
|
error => console.log('The operation was not successful: ' + error)
|
2023-10-05 12:20:00 +02:00
|
|
|
);
|
|
|
|
|
|
|
|
/*
|
|
|
|
Or we can pass only one argument if we're interested only in a positive result
|
|
|
|
*/
|
|
|
|
promise.then(
|
2024-02-23 11:17:02 +01:00
|
|
|
result => console.log('The operation was successful. It returned ' + result)
|
2023-10-05 12:20:00 +02:00
|
|
|
);
|
|
|
|
|
|
|
|
/*
|
|
|
|
Or we can pass only one argument to the method "catch" if we're interested
|
|
|
|
in negative results only.
|
|
|
|
|
|
|
|
promise.catch internally just calls promise.then(null, f)
|
|
|
|
*/
|
|
|
|
promise.catch(
|
2024-02-23 11:17:02 +01:00
|
|
|
error => console.log(error)
|
2023-10-05 12:20:00 +02:00
|
|
|
);
|
|
|
|
|
|
|
|
/*
|
|
|
|
finally gets always called
|
|
|
|
*/
|
|
|
|
promise.finally(
|
2024-02-23 11:17:02 +01:00
|
|
|
() => console.log('The execution has terminated. Bye')
|
|
|
|
);
|