##análisis de promesas
*¿Qué es asincrónico?
//异步执行
let count = 1
let timer = setTimeout(function () {
count++
console.log('in', count);
}, 1000);
console.log('out');
// out=>1000=>in
//循环执行
let count = 1
let timer = setInterval(function () {
count++
console.log('in', count);
}, 1000);
console.log('out');
setTimeout(function () {
clearInterval(timer)
console.log('clear');//第5秒后清空循环器
}, 5000);
//看不见的队列,存放着需要默默执行的命令
### 1. Proceso y subproceso
####a. Concepto y diferencia
####b. Preguntas de la entrevista
* Mapeo al navegador front-end
Chrome abre una nueva ventana, ¿es un proceso o un hilo (puede entenderse como una cooperación mutua, independientes entre sí)? => proceso (puede entenderse como un sistema completamente independiente)
* divergir
Dirección 1: ¿Comunicación de ventana (entre procesos)? => almacenamiento | cookie => La diferencia entre múltiples almacenamientos => Escenario de aplicación => Proyecto de currículum combinado
Dirección 2: principio del navegador (las entrevistas para puestos intermedios y superiores son en su mayoría)
###2.CICLO DE EVENTOS
####a. Pila de ejecución
*js lenguaje de subproceso único, ejecución de un solo paso
function func2() {
throw new Error('please check your call stack');
}
function func1() {
func2()
}
function func() {
func1()
}
func()
####b. Preguntas de la entrevista
// 执行顺序
setTimeout(() => {
console.log('count');//5.宏任务2
}, 0);
new Promise(resolve => {
console.log('new Promise');//1.属于同步进入主线程 宏任务1
resolve()
}).then(() => {
console.log('Promise then');//3.微任务1
}).then(() => {
console.log('Promise then then');//4.微任务2
})
console.log('hi');//2.同步+宏任务1
//任务拆分 : macro | micro
//同步 | 异步
event-table: puede entenderse como asíncrono para ser ejecutado
cola de eventos: cola asíncrona
Recorra sincrónicamente la pila de ejecución sincrónica y recorra asincrónicamente la cola de eventos asincrónicos.
###promiseización => encadenamiento
#### A. Teoría - Callback Hell
request.onreadystatechange = () => {
//回调后处理
}
//加时延
setTimeout(() => {
request.onreadystatechange = () => {
//回调后处理
setTimeout(() => {
//处理
request.onreadystatechange = () => {
//......
}
});
}
});
//promise化
new Promise((resolve, reject) => {
setTimeout(() => {
resolve('ok')
});
}).then(res => {
request()
}).catch(err => {
console.log(err);
})
Múltiples ejecuciones secuenciales asincrónicas => llamadas en cadena compuestas
function wait500(input) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(input + 500)
}, 500);
})
}
function wait1000(input) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(input + 1000)
}, 1000);
})
}
const p = new Promise((resolve, reject) => {
resolve(1)
})
p.then(wait500)
.then(wait1000)
.then(wait500)
.then(wait1000)
.then(res => {
console.log('end', res);
})
//全部执行完成回调
Promise.all([wait500, wait1000]).then(res => {
console.log('all end', res);
})
//有执行完成的立刻操作
Promise.race()([wait500, wait1000]).then(res => {
console.log('all end', res);
})
####b. Entrevista-promesa
* 1. Estado de la promesa - pedding | cumplido | rechazado
Ejecutor (ejecutor): Ejecutar inmediatamente cuando se recibe una nueva Promesa, recibir dos parámetros, resolver | rechazado
* 2. ¿El estado predeterminado de promesa? ¿Cómo fluye el estado? - El valor predeterminado es pedding, flujo de estado: pedding=>cumplido | pedding=>rechazado
Valor de éxito de mantenimiento interno: subdefinido | entonces capaz | promesa
Motivo de la falla de mantenimiento interno
*3.¿Valor de retorno prometido? -entonces método: recibir onFulfilled y onRejected
Si entonces, la promesa ha tenido éxito, ejecute onFulfilled, valor del parámetro
Si entonces, la promesa ha fallado, ejecute onRejected, parámetro razón
Si hay una excepción entonces, ejecute onRejected
*Seguimiento: ¿Manuscrito?
const PENDING = 'PENDING'
const FULFILLED = 'FULFILLED'
const REJECTED = 'REJECTED'
class Promise {
constructor(executor) {
//1.默认状态-PENDING
this.status = 'PENDING'
//2.内部维护的变量值
this.value = undefined
this.reason = undefined
//成功的回调
let resolve = value => {
//状态流转
this.status = FULFILLED
this.value = value
}
//失败的回调
let reason = reason => {
//状态流转
this.status = REJECTED
this.reason = reason
}
try {
executor(resolve, reject)
} catch (error) {
reject(error)
}
}
then(onFulfilled, onRejected) {
if (this.status === FULFILLED) {
onFulfilled(this.value)
}
if (this.status === REJECTED) {
onFulfilled(this.reason)
}
}
}
//异步怎么办?
const PENDING = 'PENDING'
const FULFILLED = 'FULFILLED'
const REJECTED = 'REJECTED'
class Promise {
constructor(executor) {
//1.默认状态-PENDING
this.status = 'PENDING'
//2.内部维护的变量值
this.value = undefined
this.reason = undefined
//存放回调
this.onResolvedCallbacks = []
this.onRejectedCallbacks = []
//成功的回调
let resolve = value => {
//状态流转
this.status = FULFILLED
this.value = value
this.onResolvedCallbacks.forEach(fn => fn())
}
//失败的回调
let reason = reason => {
//状态流转
this.status = REJECTED
this.reason = reason
this.onRejectedCallbacks.forEach(fn => fn())
}
try {
executor(resolve, reject)
} catch (error) {
reject(error)
}
}
then(onFulfilled, onRejected) {
if (this.status === FULFILLED) {
onFulfilled(this.value)
}
if (this.status === REJECTED) {
onFulfilled(this.reason)
}
if (this.status === PENDING) {
//存放队列
this.onResolvedCallbacks.push(() => {
onFulfilled(this.value)
})
this.onRejectedCallbacks.push(() => {
onFulfilled(this.reason)
})
}
}
}