Name: Promise constructor rejecting and then resolving or vice versa (or with sync errors)
Nitzan is writing code with Promises. He is writing the following function, but it doesn't work as expected.
function promisifyThing(thing) {
return new Promise((resolve, reject) => {
if (thing.isAThing) { resolve(thing); }
if (thing.hasErrors) { reject(thing.accumulatedErrors); }
if (thing.shouldDoAThing) { thing.doAThing((err, value) => err ? reject(err): resolve(value)); }
})
}
In the case that thing
is both isAThing
and hasErrors
, the errors get swallowed.
When resolve()
gets called, any further calls to reject()
or resolve()
are ignored. The same is true for resolve(); throw new Error()
.
Nitzan should have called either resolve()
or reject()
, not both, and only one time.
Provide a clear warning when resolve()
or reject()
are called more than once in a Promise constructor.