A promise is an object which can be returned synchronously from an asynchronous function. Every promise executor function should call resolve
and reject
function.
Impact
- If any of the executer functions are not called, promise will not be settled and remains in its pending state.
- Any
.then()
or.catch()
listeners for resolve or reject transitions will never get called. - Most code, that uses promises, expects them to
resolve
orreject
at some point in the future. In that case, if they don’t, then that code generally never gets to serve its purpose.
Characteristics
It will be in one of the three possible states:
- Fulfilled: meaning the operation fulfilled successfully.
onFulfilled()
will be called (e.g.resolve()
was called) - Rejected: meaning that operation has failed.
onRejected()
will be called (e.g.reject()
was called) - Pending: This means operation is not yet fulfilled or rejected.
Example(s)
function promise() { return new Promise((resolve,reject)=> { var result = isValid(); if(result) resolve(); }); }
Solution: For each new promise, resolve
and reject
functions are called.
function promise() { return new Promise((resolve,reject)=> { var result = isValid(); if(result) resolve(); else reject(); }); }
Guidelines
When the executor obtains the result, it should call these callbacks:
- resolve(value) — if the job finished successfully, with result value.
- reject(error) — if an error occurred, error is the error object.