liveBook · Manning

Promise

As explained in API Design Patterns

A promise is an object or abstraction representing the eventual completion or failure of an asynchronous computation.

A promise represents work that may finish later. It lets a program continue while waiting, then eventually resolves with a result or rejects with an error. section 10.2

Promises support two consumption styles: await the result, which pauses the current flow, or attach callbacks that handle success and failure asynchronously. section 10.2

When a promise-like abstraction crosses an API boundary, account for these differences:

  • Represent long-running server work with an operation resource returned by the initiating method rather than arbitrary client-side code. section 10.2
  • Retrieve the operation repeatedly until its done field is true, accepting extra requests and network traffic as the cost of polling. section 10.3.3
  • Offer a wait method when clients should ask the service to wait rather than implement repeated status requests themselves. section 10.3.3

Awaiting a factorization result

A factor function can return Promise<number[]>; callers may write `let factors = await factor(...)` or attach `.then(...)` and `.catch(...)` handlers. section 10.2

Listing 10.2 Awaiting and attaching callbacks to promises
async function factor(value: number): Promise<number[]> {
  // ...
}
 
async function waitOnPromise() {
  let factors = await factor(...);                  #1
 
  let promise = factor(...);
  let otherFactors = await promise;                 #1
}
 
function promiseCallback() {
  let promiseForFactors = factor(...);              #2
  promiseForFactors.then( (factors: number[]) => {
    // ...
  }).catch( (err) => {
    // ...
  });
}

Inspect the compact TypeScript examples showing both awaiting a promise and registering success and error callbacks. section 10.2

How API Design Patterns covers it

How deep it goes
Explains resolution, rejection, awaiting, callbacks, polling, and waiting, but does not descend into promise implementation internals.
Examples
Demonstrates factorization, await, then/catch callbacks, and a chat-room operation tracked through an API.
What it assumes
Assumes familiarity with asynchronous work and functions while introducing placeholders, resolution, rejection, and result waiting.
What you can do after
Apply promises through await or callbacks, and evaluate API operations through polling or a wait method.
How it connects
Connects promises with asynchronous computation, callbacks, Futures, and long-running operations.

Also explained in

Compare how 7 books explain promise →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of API Design Patterns. The section links point to the parts of the book it draws on.