Promise
Basic
Creation of Promise
const promise = new Promise((res, rej) => {
// do some stuffs
if() {
res("holy cow"); // param of res will be returned
} else {
rej({message: 'something', code:'404'}); // param of rej will be returned + exception will be throwed
}
});
Resolve
There are 2 ways of waiting on a promise.
awaiting on Promise
Make sure you call it from an asyn function
try {
const val = await promise;
console.log(val); // "holy cow"
} catch (exc) {
console.log(exc.message); // "something"
}
awaiting on Promise
Make sure you call it from an asyn function
promise
.then((data) => {
console.log(data); // "holy cow"
})
.catch((data) => {
console.log(data.message); // "something"
});