Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

TypeScript Promise Explained in Detail

TypeScript Promise Explained in Detail

Promise is the foundation of asynchronous programming in JavaScript, and TypeScript provides complete type support for Promise.

Through generic parameters, you can precisely specify the types of a Promise's resolved value and rejection value.


Promise workflow Create a Promise new Promise((resolve, reject) => {...}) pending Pending fulfilled ✓ rejected ✗ then() · catch() · finally()

Why Promise is needed

In JavaScript, many operations are asynchronous, such as network requests, file reads, and timers.

Promise provides a unified asynchronous programming interface, making asynchronous code easier to write and manage.

TypeScript's generic support ensures the type safety of Promise.

Concept explanation:A Promise is an object representing the eventual result of an asynchronous operation. It has three states: pending (in progress), fulfilled (successful), and rejected (failed).


Create a Promise

Create a Promise using the Promise constructor, passing in an executor function.

Example

// Create a Promise, using a generic to specify the type of the resolved value

// Promise Indicates that a string is returned on success

var

promise

=

new

Promise

<

string

(

function

(

resolve

,

reject

)

{

var

success

=

true

;

   

if

(

success

)

{

       

// Call resolve to indicate the operation succeeded, passing in the result value

        resolve

(

"Success!"

)

;

   

}

else

{

       

// Call reject to indicate the operation failed, passing in the error

        reject

(

new

Error

(

"Failed"

)

)

;

   

}

}

)

;

// Use then to handle the success case

promise.

then

(

function

(

value

)

{

    console.

log

(

"Completed: "

value

)

;

}

)

[

"catch"

]

(

function

(

error

)

{

   

// Use catch to handle the failure case

    console.

log

(

"Error: "

error.

message

)

;

}

)

;

Running result:

完成: 成功!

Generic explanation:Promise The T in it is the type of the value when the Promise is successfully resolved. This allows TypeScript to infer the return type.


Promise chaining

The then and catch methods return new Promises and can be chained.

Example

// Chained calls: each then returns a new value that is received by the next then

var

promise

=

Promise.

resolve

(

1

)

    .

then

(

function

(

n

)

{

       

// First then, n = 1

       

return

n

2

;

 

// Return 2

   

}

)

    .

then

(

function

(

n

)

{

       

// Second then, n = 2

       

return

n

10

;

 

// Return 12

   

}

)

    .

then

(

function

(

n

)

{

       

// Third then, n = 12

        console.

log

(

"Final result: "

n

)

;

       

return

n

;

   

}

)

;

console.

log

(

"Promise chain: "

promise

)

;

Running result:

最终结果: 12

Promise 链: [object Promise]

Chained calls:Each then returns a new Promise, which allows us to execute multiple asynchronous operations in sequence.


Promise.all

Promise.all waits for all Promises to complete and returns an array containing all the results.

Example

// Create three Promises

var

p1

=

Promise.

resolve

(

1

)

;

var

p2

=

Promise.

resolve

(

2

)

;

var

p3

=

Promise.

resolve

(

3

)

;

// Promise.all waits for all Promises to complete

// Returns an array containing the results of all Promises

Promise.

all

(

[

p1

,

p2

,

p3

]

)

.

then

(

function

(

results

)

{

    console.

log

(

"All completed: "

results

)

;

   

// Compute the sum

    console.

log

(

"Sum: "

results.

reduce

(

function

(

a

,

b

)

{

return

a

b

;

}

,

0

)

)

;

}

)

;

Running result:

全部完成: 1,2,3

总和: 6

Note:If any Promise fails, Promise.all immediately rejects and does not wait for the other Promises to complete.


Promise.race

Promise.race returns the result of the Promise that completes first (whether successful or failed).

Example

// Create three Promises with different delays

var

p1

=

new

Promise

(

function

(

resolve

)

{

    setTimeout

(

function

(

)

{

resolve

(

"p1"

)

;

}

,

100

)

;

}

)

;

var

p2

=

new

Promise

(

function

(

resolve

)

{

    setTimeout

(

function

(

)

{

resolve

(

"p2"

)

;

}

,

50

)

;

}

)

;

var

p3

=

new

Promise

(

function

(

resolve

)

{

    setTimeout

(

function

(

)

{

resolve

(

"p3"

)

;

}

,

30

)

;

}

)

;

// Promise.race returns the result of the first completed Promise

Promise.

race

(

[

p1

,

p2

,

p3

]

)

.

then

(

function

(

value

)

{

    console.

log

(

"First completed: "

value

)

;

}

)

;

Running result:

最先完成: p3

Application scenarios:Promise.race is often used to implement timeouts: pitting a long-running Promise against a timeout Promise.


Promise.allSettled

Promise.allSettled waits for all Promises to settle (whether successful or failed) and returns the status and result of each Promise.

Example

// Create three Promises, one of which will fail

var

p1

=

Promise.

resolve

(

"Success"

)

;

var

p2

=

Promise.

reject

(

new

Error

(

"Failed"

)

)

;

var

p3

=

Promise.

resolve

(

"Done"

)

;

// Promise.allSettled waits for all Promises to settle

// Returns the status and value/reason of each Promise

Promise.

allSettled

(

[

p1

,

p2

,

p3

]

)

.

then

(

function

(

results

)

{

    results.

forEach

(

function

(

result

,

index

)

{

       

if

(

result.

status

===

"fulfilled"

)

{

            console.

log

(

"Promise "

index

": "

result.

value

)

;

       

}

else

{

            console.

log

(

"Promise "

index

": "

result.

reason

.

message

)

;

       

}

   

}

)

;

}

)

;

Running result:

Promise 0: 成功

Promise 1: 失败

Promise 2: 完成

Difference:Promise.all stops immediately on the first failure; Promise.allSettled waits for all Promises to settle.


Promise type annotations

TypeScript's generic support makes Promise type declarations precise.

Example

// Define a function that returns a Promise

// Promise<{ name: string; age: number }> specifies the type of the returned user object

function

getUser

(

)

:

Promise

<

{

name

:

string

;

age

:

number

}

{

   

return

Promise.

resolve

(

{

name

:

"Alice"

,

age

:

25

}

)

;

}

// async function: implicitly returns a Promise

async

function

main

(

)

{

   

// await automatically infers the type of user

   

var

user

=

await getUser

(

)

;

    console.

log

(

"User: "

JSON.

stringify

(

user

)

)

;

}

main

(

)

;

Type inference:TypeScript automatically infers the return type of a Promise based on the generic parameter, allowing us to get complete type hints with async/await as well.


Notes

Best practices:Prefer the async/await syntax; it is still based on Promises under the hood, but reads like synchronous code.


Summary

Promise is the core of asynchronous programming in TypeScript.

Note:Using the async/await syntax together with Promises makes asynchronous code both type-safe and easy to read.

x