Promise对象
2021/11/26约 322 字大约 1 分钟
- Promise是一个构造函数
- Promise.prototype上包含一个.then()方法
- .then()方法用来预先指定成功和失败的回调函数
const p = new Promise()
p.then(result=>{},error=>{})
Promise.all()方法
- Promise.all()方法会发起并行的Promise异步操作,等所有的异步操作全部结束后才会执行下一步的.then操作(等待机制)。
import thenFs from 'then-fs';
const promiseArr = [
thenFs.readFile('./files/1.txt', 'utf8'),
thenFs.readFile('./files/2.txt', 'utf8'),
thenFs.readFile('./files/3.txt', 'utf8')
]
Promise.all(promiseArr).then(res=>{
console.log(res) // [ '111', '222', '333' ]
})
- 数组中Promise实例的顺序就是最终结果的顺序
Promise.race()方法
- Promise.race()方法会发起并行的Promise异步操作,只要任何一个异步操作完成,就立即执行下一步的.then操作(赛跑机制)。
import thenFs from 'then-fs';
const promiseArr = [
thenFs.readFile('./files/1.txt', 'utf8'),
thenFs.readFile('./files/2.txt', 'utf8'),
thenFs.readFile('./files/3.txt', 'utf8')
]
Promise.race(promiseArr).then(res=>{
console.log(res) //111 || 222 || 333
})
基于Promise封装异步读文件方法
import fs from 'fs';
function getFile(fpath) {
return new Promise((resolve, reject) => {
fs.readFile(fpath, 'utf8', (err, res) => {
if (err) return reject(err);
resolve(res);
});
});
}
getFile('./files/2.txt').then((res)=>{console.log(res)}).catch(err=>{console.log(err.message)})
async/await
- Async/await是ES8引入的新语法,用来简化Promise异步操作。
import thenFs from 'then-fs';
async function getFiles() {
const r1 = await thenFs.readFile('./files/1.txt', 'utf8');
console.log(r1);
const r2 = await thenFs.readFile('./files/2.txt', 'utf8');
console.log(r2);
const r3 = await thenFs.readFile('./files/3.txt', 'utf8');
console.log(r3);
}
getFiles()