TypeScript async/await Asynchronous Programming
async/await is syntactic sugar for asynchronous programming introduced in ES2017, making asynchronous code look like synchronous code.
The diagram above shows the advantages of async/await over traditional Promise: more concise code and a clearer execution flow.
Promise basics
A Promise represents the eventual result of an asynchronous operation.
Example
// Create a Promise
var
promise
=
new
Promise
(
function
(
resolve
,
reject
)
{
var
success
=
true
;
if
(
success
)
{
resolve
(
"Operation succeeded"
)
;
}
else
{
reject
(
"Operation failed"
)
;
}
}
)
;
promise.
then
(
function
(
result
)
{
console.
log
(
"Success: "
result
)
;
}
)
[
"catch"
]
(
function
(
error
)
{
console.
log
(
"Failure: "
error
)
;
}
)
;
Running result:
成功: 操作成功
async Functions
Use the async keyword to declare an asynchronous function.
Example
// An async function automatically returns a Promise
async
function
greet
(
)
:
Promise
<
string
{
return"Hello, World!"
;
}
greet
(
)
.
then
(
function
(
result
)
{
console.
log
(
"Result: "
result
)
;
}
)
;
// An async function returns a Promise
async
function
getData
(
)
{
return
{
name
:
"Alice"
,
age
:
25
}
;
}
getData
(
)
.
then
(
function
(
data
)
{
console.
log
(
"Data: "
JSON.
stringify
(
data
)
)
;
}
)
;
Running result:
结果: Hello, World!
数据: {"name":"Alice","age":25}
The await keyword
await waits for a Promise to complete and obtains its result.
Example
// simulate an async operation
function
delay
(
ms
:
number
)
:
Promise
<
string
{
return
new
Promise
(
function
(
resolve
)
{
setTimeout
(
function
(
)
{
resolve
(
"Done!"
);
}
,
ms
)
;
}
)
;
}
async
function
main
(
)
{
console.
log
(
"Start..."
)
;
var
result
=
await delay
(
100
)
;
console.
log
(
"Result: "
result
)
;
console.
log
(
"End"
)
;
}
main
(
)
;
Running result:
开始...
结果: 完成!
结束
Error handling
Use try/catch to handle asynchronous errors.
Example
function
mayFail
(
shouldFail
:
boolean
)
:
Promise
<
string
{
return
new
Promise
(
function
(
resolve
,
reject
)
{
if
(
shouldFail
)
{
reject
(
new
Error
("Operation failed"
)
)
;
}
else
{
resolve
(
"Operation succeeded"
)
;
}
}
)
;
}
async
function
handleError
(
)
{
try
{
var
result
=
await mayFail
(
true
)
;
console.
log
(
"Result: "
result
)
;
}
catch
(
error
)
{
console.
log
(
"Error caught: "
error.
message
)
;
}
}
handleError
(
)
;
Running result:
捕获错误: 操作失败
Parallel execution
Use Promise.all to execute multiple asynchronous operations in parallel.
Example
function
fetchUser
(
id
:
number
)
:
Promise
<
{
id:
number
;
name
:
string
}
{
return
Promise.
resolve
(
{
id
:
id
,
name
:
"User"
id
}
)
;
}
async
function
main
(
)
{
// Execute sequentially
console.
time
(
"Sequential"
)
;
var
user1
=
await fetchUser
(
1
)
;
var
user2
=
await fetchUser
(
2
)
;
console.
log
(
"Sequential complete: "
user1.
name
", "
user2.
name
)
;
console.
timeEnd
(
"Sequential"
)
;
// Execute in parallel
console.
time
(
"Parallel"
)
;
var
results
=
await Promise.
all
(
[
fetchUser
(
1
)
,
fetchUser
(
2
)
]
)
;
console.
log
(
"Parallel complete: "
results
[
0
]
.
name
", "
results
[
1
]
.
name
)
;
console.
timeEnd
(
"Parallel"
)
;
}
main
(
)
;
Running result:
串行完成: User1, User2
并行完成: User1, User2
Advantages of async/await over Promise
- More concise and readable code
- Synchronous code style
- Better error stack
- Easy to debug
Summary
- **async:** declares an asynchronous function
- **await:** waits for a Promise
- **Error handling:** try/catch
- **Parallelism:** Promise.all