前言
基于es6模块的按需导入和导出,本文介绍了promise构造函数,同步任务和异步任务的执行机制,以及宏任务和微任务的执行顺序
一、promise是什么?
概述: promise是一个构造函数,用来解决回调地狱的现象。
1.回调地狱
多层回调函数嵌套,就造成了回调地狱的现象,如图所示:
2.Promise
- 创建promise实例 :
const p = new Promise(); - promise.prototype原型链上的.then()方法:用来预先指定成功和失败的回调函数
p.then(result=>{},error=>{}); - all和 race
import fs from 'then-fs';
const proAll = [
fs.readFile('./files/1.txt','utf8'),
fs.readFile('./files/2.txt','utf8'),
];
Promise.all(proAll).then(result =>{
console.log(result);
});
Promise.race(proAll).then(result =>{
console.log(result);
});
- await和async
import thenfs from 'then-fs';
async function getall() {
const r1 = await thenfs.readFile('./files/1.txt', 'utf8')
console.log(r1);
const r2 = await thenfs.readFile('./files/2.txt', 'utf8')
console.log(r2);
}
getall()
二、EventLoop
1.同步任务和异步任务
为了防止某个耗时任务导致程序假死的问题, Javascript把待执行的任务分为了两类:
同步任务(synchronous)
- 也叫做非耗时任务,指的是在主线程上排队执行的那些任务。
- 只有前一个任务执行完毕,才能执行后一个任务。
异步任务(asynchronous)
- 又叫做耗时任务,异步任务由JavaScript委托给宿主环境(浏览器或者nodejs环境)进行执行。
- 当异步任务执行完成后,会通知Javascript主线程执行异步任务的回调函数 。
2.同步任务和异步任务的执行过程
测试代码如下:
import thenFs form 'then-fs';
console.log('A');
thenFs.readFile('./files/1.txt','utf8').then(dataStr =>{
console.log('B');
});
setTimeout(()=>{
console.log('C');
},0);
console.log('D');
三、宏任务和微任务
每一个宏任务执行完之后,都会检查是否存在待执行的微任务。宏任务可以理解为是执行步骤复杂的异步任务,微任务可以理解为执行起来较为快的同步任务。
测试代码如下:
setTimeout(()=>{
console.log('1');
});
new Promise(resolve=>{
console.log('2');
resolve();
}).then(()=>{
console.log('3');
});
console.log('4');
|