当前位置:网站首页>nodeJs--async/await
nodeJs--async/await
2022-08-04 00:06:00 【H5_ljy】
一、什么是async/await
async/await是es7推出的一套关于异步的终极解决方案;主要作用就是转异步为同步。
二、async/await语法格式
//可写一个函数返回的是异步的promise对象,也可以定义一个异步函数;
function fn(){
return new Promise((resolve,reject)=>{
resolve(666)
})
}
let p1=new Promise((n1,n2)=>{ //也可以直接写一个promise对象
n1(999)
})
// 在需要使用上面异步函数的函数前面,加上async声明,声明这是一个异步函数
async function fn2(){
// 在异步函数前面加上await,函数执行就会等待用await声明的异步函数执行完毕之后,在往下执行
let a1=await fn()
let p=await p1
console.log(a1,p)
}
fn2()
注意:async/await不能捕获错误,可以使用try/catch来进行错误的捕获
function fn() {
return new Promise((resolve, reject) => {
resolve(666)
})
}
let p1 = new Promise((n1, n2) => {
n1(999)
})
async function fn2() {
try {
let a1 = await fn()
let p = await p1
console.log(a1, p)
} catch (err) {
console.log(err)
}
}
fn2()
小结:
1.async函数在声明形式上和普通函数没有区别,函数声明式,函数表达式,对象方法,class方法和箭头函数等都可以声明async函数。
2.任何一个await语句后面的 Promise 对象变为reject状态,那么整个async函数都会中断执行。
3.async函数返回的 Promise 对象,必须等到内部所有await命令后面的 Promise 对象执行完,才会发生状态改变,除非遇到return语句或者抛出错误。也就是说,只有async函数内部的异步操作执行完,才会执行then方法指定的回调函数。
边栏推荐
- 2021年数据泄露成本报告解读
- R3LIVE论文学习(二):VIO子系统
- The longest substring that cannot have repeating characters in a leetcode/substring
- XSLT – 编辑 XML概述
- Sqlnet. Ora file with the connection of authentication test
- 2022/8/3 Exam Summary
- The problem of disorganized data output by mnn model
- 面试必问的HashCode技术内幕
- 通过whl安装第三方包
- ping数据包中的进程号
猜你喜欢
随机推荐
七夕?new一个对象
重新认识浏览器的渲染过程
YOLOv7改进之二十二:涨点神器——引入递归门控卷积(gnConv)
JS获得URL超链接的参数值
sqlnet.ora文件与连接认证方式的小测试
libnet
[Miscellaneous] How to install the specified font into the computer and then use the font in the Office software?
并查集详解
The curl using guide
【杂项】如何将指定字体装入电脑然后能在Office软件里使用该字体?
The world's first mass production, with the most fixed points!How does this AVP Tier1 lead?
c语言分层理解(c语言指针(上))
Justin Sun: Web3.0 and the Metaverse will assist mankind to enter the online world more comprehensively
查看CUDA、pytorch等的版本号
高斯推断推导
c语言分层理解(c语言操作符)
机器学习——库
Three.js入门详解
详谈RDMA技术原理和三种实现方式
Nanoprobes 棕榈酰纳米金相关说明书