Javascript Fundamentals ยท Promises & Async

Wrap a callback API in a Promise

constructing a Promise

Wrap a callback API in a Promise

You want to run a few reads in order, or wait for one call before starting the next. An older API hands you its result through a callback instead of returning it, so you cannot chain the next step on a value that is not there yet.

A Promise is a placeholder for a value that is not ready yet. You create one with new Promise, handing the constructor a function that receives two callbacks: resolve and reject. Call resolve(value) when the work succeeds and reject(error) when it fails. Whichever you call first settles the promise; the other is ignored.

A Node-style callback takes (error, value) and is invoked once when the work finishes. Promises compose better, so a common job is to wrap such an API:

function promisify(fn) {
  return (input) =>
    new Promise((resolve, reject) => {
      fn(input, (error, value) => {
        if (error) {
          reject(error);
        } else {
          resolve(value);
        }
      });
    });
}

The returned function starts the work and returns a promise immediately. When the callback eventually fires, resolve or reject settles that promise, and any .then attached to it runs.

Export promisify from index.js. Your job is to settle the promise from the callback: resolve with the value, or reject with the error.

Challenge

An older API reports its result through a callback, so you cannot chain the next step on the value it returns. Wrap it once and the result becomes a promise you can work with.

Export a promisify function from index.js. It takes a callback-style function fn(input, callback), where callback is called as callback(error, value), and returns a new function. Calling the returned function with an input must start fn and return a Promise that resolves with value when the callback reports no error, and rejects with error when it does.

index.js
export function promisify(_fn) {
  return () => Promise.resolve('');
}

export function render(mount) {
  const button = document.createElement('button');
  button.textContent = 'Load';
  const output = document.createElement('p');
  output.textContent = 'idle';

  const readName = promisify((input, callback) => {
    setTimeout(() => callback(null, `Hello, ${input}`), 10);
  });

  button.addEventListener('click', () => {
    readName('Ada').then((message) => {
      output.textContent = message;
    });
  });

  mount.append(button, output);
}

No test run yet

The Test is hidden. Run it to check the Challenge โ€” you only see the result, never the test source.