Promises
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
Promise
var promiseInstance = new Promise(function(resolve, reject) {
// call resolve(...) to resolve the request
// call reject(...) to reject the request
});
const someFn = function() {
var respPromise = new Promise(function(resolve, reject) {
// call resolve(...) to resolve the request
// call reject(...) to reject the request
});
return respPromise;
}
const promise1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('foo');
}, 300);
});
promise1.then((value) => {
console.log(value);
// Expected output: "foo"
});
console.log(promise1);
// Expected output: [object Promise]
Promise.resolve
The Promise.resolve() static method "resolves" a given value to a Promise. If the value is a promise, that promise is returned; if the value is a thenable, Promise.resolve() will call the then() method with two callbacks it prepared; otherwise the returned promise will be fulfilled with the value.
An example could be that you call a function and wrap that call in Promise.resolve(someFn()). The function you call could then return a value (e.g. a boolean) or it could return back a Promise instance itself. You can then handle the response of that function as if it returns a promise.
const promise1 = Promise.resolve(123);
promise1.then((value) => {
console.log(value);
// Expected output: 123
});
const someHandlerFn = function(someParam) {
var respPromise = new Promise(function(resolve, reject) {
if (typeof someParam === 'string' && someParam.length > 0) {
resolve(true);
}
else {
reject();
}
});
return respPromise;
};
try {
Promise.resolve(someHandlerFn('some string')).then(
function(resp) {
// Handle resp
},
function() {
// Handle rejection
}
);
}
catch(e) {
console.warn(e);
}