# async 写法与执行流程
| async function foo() { |
| console.log('foo function start~') |
| } |
| |
| foo() |
| console.log('foo function end~') |
| |
| |
# 和普通函数的区别一 返回值
# 返回一个值
| async function foo() { |
| console.log('foo function start~') |
| return { |
| then: function (resolve) { |
| resolve('22333') |
| } |
| } |
| } |
| |
| |
| const promise = foo() |
| |
| promise.then(res => { |
| console.log(res) |
| }) |
| |
| console.log('这行代码会在中间执行') |
# 返回 thenable
| async function foo() { |
| console.log('foo function start~') |
| return { |
| then: function (resolve) { |
| resolve('22333') |
| } |
| } |
| } |
| |
| |
| const promise = foo() |
| |
| promise.then(res => { |
| console.log(res) |
| }) |
| |
| console.log('这行代码会在中间执行') |
# 返回 Promise
| async function foo() { |
| console.log('foo function start~') |
| return new Promise(resolve => setTimeout(() => resolve('promise~') , 2000)) |
| } |
| |
| |
| const promise = foo() |
| |
| promise.then(res => { |
| console.log(res) |
| }) |
| |
| console.log('这行代码会在中间执行') |
# 和普通函数的区别二 异常
| async function foo() { |
| console.log('foo function start~') |
| throw new Error('throw new Error') |
| } |
| |
| foo().catch(err => { |
| console.log(err) |
| }) |
| |
| console.log('foo function end~') |
# await 返回值
# 函数返回 Promise
| function requestData() { |
| return new Promise((resolve, reject) => setTimeout(() => resolve(233), 5000)) |
| } |
| |
| async function foo() { |
| |
| const res = await requestData() |
| console.log(res) |
| |
| |
| console.log('---------------') |
| |
| |
| const res2 = await requestData() |
| console.log(res2) |
| } |
| |
| foo() |
# 直接返回 Promise
| async function foo() { |
| const res = await new Promise(resolve => resolve(233)) |
| console.log(res) |
| } |
| |
| foo() |
# 普通值
| async function foo() { |
| const res = await 233 |
| console.log(res) |
| } |
| |
| foo() |
# thenable
| async function foo() { |
| const res = await { |
| then: function (resolve, reject) { |
| resolve(233) |
| } |
| } |
| console.log(res) |
| } |
| |
| foo() |
# reject
| function requestData() { |
| return new Promise((_, reject) => setTimeout(() => reject(233), 2000)) |
| } |
| |
| async function foo() { |
| const res = await requestData() |
| |
| console.log(res) |
| console.log('------------') |
| } |
| |
| foo().catch(err => console.log(err)) |