走进ES6的世界:基础语法入门指南4

简介: 走进ES6的世界:基础语法入门指南

10、async 函数

10.1、基本用法

用于声明异步函数,返回值为一个 Promise 对象,它以类似 同步 的方式来写异步方法。可以使用then方法添加回调函数。当函数执行的时候,一旦遇到await就会先返回,等到异步操作完成,再接着执行函数体内后面的语句。(async表示函数里有异步操作,await表示紧跟在后面的表达式需要等待结果。)

下面是一个例子。

async function getStockPriceByName(name) {
  const symbol = await getStockSymbol(name);
  const stockPrice = await getStockPrice(symbol);
  return stockPrice;
}
getStockPriceByName('goog').then(function (result) {
  console.log(result);
});

async 函数有多种使用形式。

// 函数声明
async function foo() {}
// 函数表达式
const foo = async function () {};
// 对象的方法
let obj = { async foo() {} };
obj.foo().then(...)
// 箭头函数
const foo = async () => {};

10.2、返回 Promise 对象

async函数返回一个 Promise 对象。

async函数内部return语句返回的值,会成为then方法回调函数的参数。

async function f() {
  return 'hello world';
}
f().then(v => console.log(v))
// "hello world"

上面代码中,函数f内部return命令返回的值,会被then方法回调函数接收到。

async函数内部抛出错误,会导致返回的 Promise 对象变为reject状态。抛出的错误对象会被catch方法回调函数接收到。

async function f() {
  throw new Error('出错了');
}
f().then(
  v => console.log('resolve', v),
  e => console.log('reject', e)
)
//reject Error: 出错了

10.3、await 命令

  • await 后面接 Promise

    1.await p1相当于是 p1.then,并且只是成功态的then

    2.await 和 then 的区别就是:then还需要传回调进去,但 await 可以直接得到值

async function(){
  const p1 = Promise.resolve(300) //一个成功态的promise对象,且传了result为300
  const res = await p1 // return 值
  console.log(res) // 300
}
await 和 then 的区别:
fn().then(
  data=>{
    console.log(data)
  }
)
//await直接通过返回值来接收data, return data
const res = await fn()  
  • await 接收值

    1.await后面跟的不是promise对象而是数值时,会自动包装成成功态的promise对象

     2.并且传值给 resolve 为400

async function(){  
  const res = await 400 //Promise.resolve(400) 
  console.log(res) //400
 }
  • await 接 async 函数
async function fn(){
  return 400
}
async function(){
  const res = await fn() //fn()会返回promise对象,原理一样
  console.log(res) //400
}
  • await 接promise 为空

    1.什么都打印不出来

    2.因为 new Promise 里面没有任何状态改变,而await一直在等待状态改变

    3.只有状态改变了,await才会允许执行后面的代码

async function(){
  const p = new Promise(()=>{})
  const res = await p
  console.log(res)
  console.log("success")
}
  • await 接 promise 为 error

     1.会出现报错

     2.await相当于成功态的 .then ,都没有成功,因此不会执行后面的代码

     3.解决:使用 try…catch 偷偷解决掉 error,保证代码运行

——捕获到错误就不会影响后面的输出

async function(){
  const p = Promise.reject("error")
  const res = await p
  console.log(res)
  console.log("success")
})   //什么都打印不出来
async function(){
  const p = Promise.reject("error")
  try{
    const res = await p
    console.log(res)
  }catch(error){
    console.log(error)
  }
  console.log("success")
}   //打印出 error 和 success

10.4、使用await的注意点

1、await命令只能用在async函数之中,如果用在普通函数,就会报错。

2、await命令后面的Promise对象,运行结果可能是rejected,所以最好把await命令放在try...catch代码块中。

console.log(‘reject’, e)
)
//reject Error: 出错了
### 10.3、await 命令
- await 后面接 Promise
  1.await p1相当于是 `p1.then`,并且只是成功态的`then`
  2.await 和 then 的区别就是:then还需要传回调进去,但 await 可以直接得到值
async function(){
const p1 = Promise.resolve(300) //一个成功态的promise对象,且传了result为300
const res = await p1 // return 值
console.log(res) // 300
}
await 和 then 的区别:
fn().then(
data=>{
console.log(data)
}
)
//await直接通过返回值来接收data, return data
const res = await fn()
- await 接收值
  1.await后面跟的不是promise对象而是数值时,会自动包装成成功态的promise对象
  2.并且传值给 resolve 为400
async function(){
const res = await 400 //Promise.resolve(400)
console.log(res) //400
}
- await 接 async 函数
```javascript
async function fn(){
  return 400
}
async function(){
  const res = await fn() //fn()会返回promise对象,原理一样
  console.log(res) //400
}
  • await 接promise 为空

    1.什么都打印不出来

    2.因为 new Promise 里面没有任何状态改变,而await一直在等待状态改变

    3.只有状态改变了,await才会允许执行后面的代码

async function(){
  const p = new Promise(()=>{})
  const res = await p
  console.log(res)
  console.log("success")
}
  • await 接 promise 为 error

    1.会出现报错

    2.await相当于成功态的 .then ,都没有成功,因此不会执行后面的代码

    3.解决:使用 try…catch 偷偷解决掉 error,保证代码运行

——捕获到错误就不会影响后面的输出

async function(){
  const p = Promise.reject("error")
  const res = await p
  console.log(res)
  console.log("success")
})   //什么都打印不出来
async function(){
  const p = Promise.reject("error")
  try{
    const res = await p
    console.log(res)
  }catch(error){
    console.log(error)
  }
  console.log("success")
}   //打印出 error 和 success

10.4、使用await的注意点

1、await命令只能用在async函数之中,如果用在普通函数,就会报错。

2、await命令后面的Promise对象,运行结果可能是rejected,所以最好把await命令放在try...catch代码块中。

目录
相关文章
|
网络协议 应用服务中间件 nginx
解决 nginx 启动错误host not found in upstream "XXXX.com“
在前置机上利用nginx进行反向代理的时候,我们会配置proxy_pass。在启动nginx的会报如下错误:host not found in upstream "XXXX.com“
8459 0
|
6月前
|
人工智能 缓存 自然语言处理
阿里云AI大模型节省计划解读:优势、使用、资源包、折扣信息及问题解答FAQ
阿里云AI模型节省计划是百炼平台推出的折扣方案,支持按量付费用户通过承诺周期内月消费金额,享最高5.3折优惠。覆盖千问、向量、语音、图像等全系阿里直供模型,自动抵扣,灵活开通,显著降低大模型调用成本。阿里云百炼AI大模型平台:https://t.aliyun.com/U/fPVHqY
655 0
|
11月前
|
存储 运维 对象存储
阿里云轻量应用服务器——2026个人及中小企业首选云服务器
阿里云轻量应用服务器,以轻量化、贴近应用、账单清晰、持续进化为核心优势,预装多种应用镜像,200M峰值带宽,支持网站搭建、小程序、电商独立站等多场景,38元/年起,是2026年个人与中小企业上云首选。
3256 11
|
前端开发 JavaScript
|
存储 供应链 物联网
区块链技术的未来发展趋势:革新、挑战与机遇
区块链技术的未来发展趋势:革新、挑战与机遇
885 8
|
数据采集 机器学习/深度学习 存储
【数据说话】当下的Python就业前景如何
以上便是我们做的一些微小工作,希望能给大家带来些帮助。当然,本案例中所有数据来自上述招聘网站的公开数据,与真实的市场需求有可能存在偏差,仅供参考。
846 0
|
数据采集 数据挖掘 数据格式
Pandas的用法
【7月更文挑战第9天】Pandas的用法
337 3
|
jenkins 持续交付 开发工具
Jenkins 构建报错:index-pack died of signal 15
Jenkins 构建报错:index-pack died of signal 15
628 2