1.Promoise
- Promoise的三种状态
有异步操作时,可以给异步操作包装一个promoise,之后会有三种状态
- ... pending:等待状态,比如正在进行网络请求,或者定时器没有到时间
- √ fulfilled:完成(满足)状态,当我们主动回调了resolve时,就处于该状态,并会回调.then()
- x rejected:拒绝状态,当我们主动回调了reject时,就处于该状态,并会回调.catch()
Promoise的方法 | |||
---|---|---|---|
状态[[PromiseState]] | 触发方式: 执行参数函数 | 结果: 执行参数函数 | 结果[[PromiseResult]] |
pending | 下面两个都不执行 | 无 | undefined |
fulfilled | resolve('my成功') | then( params1执行, params2 ) finally() | my成功 |
rejected | reject('my失败') | then( params1, params2执行 ) tatch() finally() | my失败 |
const pro1 = new Promise((resolve,reject) => {
// resolve('我的成功')
reject('我的失败')
})
pro1.then(res=>{
console.log('res===',res)
},err=>{
console.log('err===',err)
}).catch(err=>{
console.log('catch的err===',err)
}).finally(()=>{
console.log('完成')
})
console.dir(pro1)
// 注:如果同时执行resolve() reject(),谁在前先执行谁,后面的不执行
// 因为promise是不可逆的
- then方法
then方法返回一个状态为pending的promise的实例对象,
在then方法里return一个***,则这个是promise的实例对象状态改为fulfilled
在then方法里return一个错误,则这个promise的实例对象状态改为rejected
注:如果不return,then方法会默认return undefined
触发方法 | |
return 任一数据类型/错误 *默认方法 return undefined | |
return 一个函数(如果是promise,则可以通过resolve直接传参) | |
待补充,修改 |
- catch方法
当promise状态改为rejected时执行
但promise执行体中出现错误代码时执行
2.async和await
- async
async关键字,将函数标记为异步函数,函数下面得其他js可以继续执行,不必等待该函数执行完毕
async标记后的函数返回值,始终是一个promise
- await
等待promise完成后,直接返回最终结果 ≈≈≈≈≈ then
- 注意陷阱
*如果n个await需要并发执行,则需要用的promise.all
*如果n个await第n需要用到n-1的值,则正常书写,n-1执行完毕后,才会执行n
*forEach和map中的异步操作(await),js会直接循环完毕,而不是等当前await执行完毕再去循环-执行下一个await
*for循环和for await中的异步操作(await),每次循环内的await执行完毕后才会执行下一次序循环
*await只能在异步函数(async)和顶级模块体中使用
3.class类
// 类的基本用法
class Animal{
constructor(name,age) {
this.name = name
this.age = age
}
sayName(){
return this.name
}
}
let pig = new Animal('小猪',22)
console.log(pig.sayName()) // 小猪
// 类的继承;重写父类的方法
class Dog extends Animal{
constructor(name,age,color) {
super(name,age)
// super(name,age) === Animal.call(this,name,age)
// 把Dog的this的指向Animal,从而继承Animal的name和age
this.color = color
}
sayName(){
return `重写的父类方法 且 继承父类的name和age属性 name:${this.name}color:${this.age}`
}
}
let d1 = new Dog('小黄',33,'red')
console.log(d1) // 重写的父类方法 且 继承父类的name和age属性 name:小黄color:33
4.模块化
// export导出1
export const name = "张三";
export function fn(){
return '我是函数'
}
// export导出2
const myname = "李四";
function sayName (){
return '我是李四'
}
export {myname,sayName}
// export default导出
const obj = {
name:'王五',
age:33
}
export default obj
<script type="module">
import myobj,{name,fn,myname,sayName} from './js/moduleA.js'
import * as f from './js/moduleA.js'
console.log('export导出1===',name,fn)
console.log('export导出2===',myname,sayName)
console.log('export default导出===',myobj)
console.log('导入所有===',f)
</script>
5.标题一
xxxxxxxxxxxxxxxxx
4.标题一
xxxxxxxxxxxxxxxxx
5.标题一
xxxxxxxxxxxxxxxxx