在传统异步编程,想要顺序获取异步函数的执行结果会导致回调地狱问题:
var fs = require("fs");
fs.readFile('./1.txt', 'utf8', (err, ret1) => {
console.log(ret1);
fs.readFile('./2.txt', 'utf8', (err, ret2) => {
console.log(ret2);
fs.readFile('./3.txt', 'utf8', (err, ret3) => {
console.log(ret3);
})
})
})
Promise是以上回调地狱问题的一种解决方案。
promise封装异步操作:
function readTxt(url) {
return new Promise((resolve, reject) => {
fs.readFile(url, "utf8", (err,ret) => {resolve(ret.toString())})
})
}
//备注:以下是封装promise异步函数的两种方式
①let promise = new Promise( (resolve,reject)=>{ 异步成功resolve(ret),否则reject(err) }})
②function promise () {
return new Promise ( (resolve,reject)=>{ 异步成功resolve(ret),否则reject(err) })
}
顺序获取promise函数的执行结果(then方式)
readTxt("./1.txt")
.then(r1 => {alert(r1); return readTxt("./2.txt")})
.then(r2 => {alert(r2); return readTxt("./3.txt")})
.then(r3 => {alert(r3);})
顺序获取promise函数的执行结果(async/await方式,我认为是一种语法优化)
async function readAll() {
let r1 = await readTxt("./1.txt");
let r2 = await readTxt("./2.txt");
let r3 = await readTxt("./3.txt");
alert(r1);alert(r2);alert(r3);
}
readAll();
注:
async关键字:让普通函数变成返回promise对象的异步函数
await关键字:用于异步函数中,后面只能写promise对象,用来暂停异步函数向下执行,直到promise返回结果
手写promise: