A Better Way to Create Promises in JavaScript
If you have created a `promise` with `resolve` and `reject` functions called inside the promise constructor, there is a better way to write a promise and that is using async/await
because async functions return a promise by default. Let me show you by an example:
const promiseFn = () => {
return new Promise((resolve, reject) => {
resolve('Resolved');
});
};const promiseFn2 = async () => {
return 'Resovlved';
};const promiseFn3 = () => {
return new Promise((resolve, reject) => {
reject(new Error('ERROR!'));
});
};const promiseFn4 = async () => {
throw new Error('ERROR!');
}promiseFn().then(data => console.log('Resolved1', data));
promiseFn2().then(data => console.log('Resolved2', data));
promiseFn3().catch(data => console.log('Rejected1', data.message));
promiseFn4().catch(data => console.log('Rejected2', data.message));
`promiseFn` and `promiseFn3` is created using a `Promise` constructor with `resolve` and `reject` arguments and `promiseFn2` and `promiseFn4` is simply called using an `async` keyword and return and throw keywords inside the function. `promiseFn` is equivalent to `promiseFn2` and `promiseFn3` is equivalent to `promiseFn4` in especially in the case it is awaited or then/catch function is called
After execution of the code, you will see the oufput as shown below
We can reduce the lines of code using async await instead of creating promise constructor.
But in case of functions like setTimeout, setInterval etc, we can not use async await directly. We have to use promise to resolve and then use async await for the assigned promise.
const timeOutPromise = new Promise((resolve) => setTimeout(() => { resolve('wait completed') }, 1000));