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






