Skip to content
This repository has been archived by the owner on Oct 7, 2020. It is now read-only.

Latest commit

 

History

History
29 lines (19 loc) · 1.01 KB

File metadata and controls

29 lines (19 loc) · 1.01 KB

Use Case #3

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)); }
    })
}

What happens

In the case that thing is both isAThing and hasErrors, the errors get swallowed.

Why it happens

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.

What can we maybe do better

Provide a clear warning when resolve() or reject() are called more than once in a Promise constructor.