Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 2

Wrap a callback API in a Promise in JavaScript

19 A promise built by hand around a callback

fair

Wrap an error-first callback API in a promise with the new Promise constructor. Then answer four questions about the executor: when does it run, what happens if it throws, what happens if you resolve twice, and what happens if you reject after resolving?

Stuck? Three hints, smallest first
  1. 1. The executor runs synchronously, right there in the constructor. Only the settlement is deferred.
  2. 2. A throw inside the executor is turned into a rejection for you.
  3. 3. A promise settles once. Every later resolve or reject is a no-op, silently.

The answer

const bank = {
  balances: { 'LAG-01': 45000, 'ABJ-02': 12000 },
  lookup(account, callback) {
    // Deliberately asynchronous: the callback never fires in the same tick.
    Promise.resolve().then(() =>
      account in this.balances
        ? callback(null, this.balances[account])
        : callback(new Error('no such account: ' + account))
    );
  },
};

const balanceOf = (account) =>
  new Promise((resolve, reject) => {
    bank.lookup(account, (err, value) => (err ? reject(err) : resolve(value)));
  });

let executorRan = false;
new Promise(() => { executorRan = true; });

const order = [];
const watching = balanceOf('LAG-01').then((v) => order.push('resolved ' + v));
order.push('the line after the call');
await watching;

const missing = await balanceOf('nope').then(() => 'resolved', (e) => e.message);
const twice = await new Promise((resolve) => { resolve('first'); resolve('second'); });
const thenRejected = await new Promise((resolve, reject) => { resolve('kept'); reject(new Error('ignored')); });
const blewUp = await new Promise(() => { throw new Error('executor blew up'); }).catch((e) => e.message);

console.log('balance   :', await balanceOf('ABJ-02'));
console.log('missing   :', missing);
console.log('order     :', order);
console.log('settled twice:', twice, ' rejected after resolving:', thenRejected);

Output


      
8 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('the wrapper resolves with the value', await balanceOf('LAG-01'), 45000);
test('and rejects with the error', missing, 'no such account: nope');
test('the executor runs synchronously, inside the constructor', executorRan, true);
test('but settlement is always asynchronous, so the next line runs first', order, ['the line after the call', 'resolved 45000']);
test('resolving twice keeps the first value', twice, 'first');
test('rejecting after resolving is ignored', thenRejected, 'kept');
test('a throw inside the executor becomes a rejection', blewUp, 'executor blew up');
test('and the promise is a real promise, not a thenable', (await balanceOf('LAG-01').then(() => balanceOf('LAG-01'))) instanceof Promise, false);

new Promise is for exactly one job: wrapping something that is not already a promise. If you are writing it around a function that already returns one, you have written the deferred anti-pattern and added a layer that can only lose errors.

The four questions are the whole contract. The executor is synchronous — so any setup you do there has already happened by the time the constructor returns, and a throw in it is caught and converted, which is why you never need a try around your own reject call. Settlement is asynchronous — the fourth assertion shows the line after the call running first, which is guaranteed even if the value was available immediately. And settlement is final — the fifth and sixth assertions show a second resolve and a late reject being dropped without a word, which makes a double-callback bug in the wrapped API invisible rather than fatal.

The last assertion is a small trap of its own: await unwraps, so the value inside is a number and not a promise. Returning a promise from a then handler flattens it rather than nesting it, which is exercise 30.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.