一、promise并不是完美解决方案
如果Promise.then()使用过多,回调地域依然存在。
new Promise((resolve, reject) => {
setTimeout(() => resolve(111), 1000);
}).then(data => {
console.log(data);
new Promise((resolve, reject) => {
setTimeout(() => resolve(222), 2000)
}).then(data => {
console.log(data);
new Promise((resolve, reject) => {
setTimeout(() => resolve(333), 3000)
}).then(data => {
console.log(data);
})
})
})
二、async/await
简介:
建立在Promise之上异步编程新方法,更优雅的解决异步,es8新增promise语法糖。
相对于 Promise 和回调,它的可读性和简洁度都更高,更好地处理 then 链。
目的:
简化使用多个 promise 时的同步行为,并对一组 Promises 执行某些操作。
// 定时器嵌套
function f1() {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(111), 1000);
}).then(data => console.log(data));
}
function f2() {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(222), 2000);
}).then(data => console.log(data));;
}
function f3() {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(333), 3000);
}).then(data => console.log(data));;
}
async function timeoutFn() {
await f1(); // 开始执行第一个异步函数
await f2(); // 第一个执行完,开始执行第二个异步函数
await f3(); // 第二个执行完,开始执行第三个异步函数
}
timeoutFn();
三、async
异步的意思,函数前加上async,声明一个函数是异步的,那么该函数就会返回一个 Promise。
返回的promise成功还是失败,看函数return
async function main(){
// 1. 如果返回的是非 Promise 对象,所有数据类型。
// 返回成功的promise
return 'iloveyou';
//2. 如果返回的是 Promise 对象
// 看返回的promise是成功还是失败,成功则成功,失败则失败。
return new Promise((resolve ,reject) => {
resolve('123');
reject('失败');
});
//3. 函数抛出异常 promise对象也是失败的
throw '有点问题';
}
// let result = main();
// console.log(result);
main().then(value => {}, reason=>{
console.error(reason);
});
四、await
await 异步等待的意思等待一个异步方法执行完成,后面常放返回promise对象表达式,必须放在async函数中。
如果await中promise失败,就用try、catch进行捕获。
try 放到成功的操作
catch 放失败的操作
// await必须写在async函数中,但async函数中可以没有await
async function main() {
let result = await Promise.resolve('OK');
console.log(result);
// 1、promise为promise对象,返回成功的值
let one = await 1;
console.log(one);//
///2、其他值 返回变量值
}
五、结合
const fs = require('fs');
const util = require('util');// promisify
// 把promise方法变成promise版本的函数
const mineReadFile = util.promisify(fs.readFile);
async function main() {
try {
//读取第一个文件的内容
const one = await mineReadFile('./resource/x.html');
//读取第二个文件的内容
const two = await mineReadFile('./resource/2.html');
//读取第三个文件的内容
const three = await mineReadFile('./resource/3.html');
console.log(one + two + three);
} catch (e) {
console.log('文件读取失败, 文件路径为' + e.path);
// console.log(e);
}
}
main();