Promise.resolve() code example
Example 1: js create a promise
/*
A Promise is a proxy for a value not necessarily known when the promise is created.
It allows you to associate handlers with an asynchronous action's eventual success
value or failure reason.
*/
let promise = new Promise((resolve , reject) => {
fetch("https://myAPI")
.then((res) => {
// successfully got data
resolve(res);
})
.catch((err) => {
// an error occured
reject(err);
});
});
Example 2: resolve vs return promise js
In simple terms, inside a then handler function:
A) When x is a value (number, string, etc):
- return x is equivalent to return Promise.resolve(x)
- throw x is equivalent to return Promise.reject(x)
B) When x is a Promise that is already settled (not
pending anymore):
- return x is equivalent to return Promise.resolve(x),
if the Promise was already resolved.
- return x is equivalent to return Promise.reject(x),
if the Promise was already rejected.
C) When x is a Promise that is pending:
- return x will return a pending Promise, and it will
be evaluated on the subsequent then.
Read more on this topic on the Promise.prototype.then() docs.
Example 3: Promise.resolve
var original = Promise.resolve(33);
original.then( val => console.log('origianl', val);
var cast = Promise.resolve(original);
cast.then(function(value) {
console.log('value: ' + value);
});
console.log('original === cast ? ' + (original === cast));
// logs, in order:
// original === cast ? true
// value: 33
Example 4: immediate promise resolve
Promise.resolve().then(() => {
console.log('resolved');
});
console.log('end');
// end
// resolve