Promise
回调地狱
const fs = require('fs');fs.readFile('./a.txt', 'utf-8', (err, data) => {if(err) throw err;console.log(data);fs.readFile('./b.txt', 'utf-8', (err, data) => {if(err) throw err;console.log(data);fs.readFile('./c.txt', 'utf-8', (err, data) => {if(err) throw err;console.log(data);})})})
Promise
Promise对象可以解决回调地狱的问题
Promise可以理解为一个容器,里面可以编写异步程序的代码
基本用法
const fs = require('fs');//1、创建对象let p = new Promise((resolve, reject) => {//把异步任务成功的结果传递给resolve函数,把失败的结果传递给reject函数fs.readFile('./a.txt', 'utf-8', (err, data) => { //读取文件的时候,没有错误err=null, 有错误err={} err ? reject(err) : resolve(data);})});//2、获取成功失败结果p.then(res => console.log(res), err => console.log(err));
Promise三种状态
pending fulfilled rejected
最初状态pending, 等待中,此时promise的结果为undefined;
当调用resolve(data)时, 状态变为 fulfilled
当调用reject(err)时, 状态变为 error
当达到最终的fulfilled或rejected时,promise的状态就不会再改变了(所以多次调用resolve,后面的resolve都无效,只取第一次)
// 1、创建对象
let p = new Promise((resolve, reject) => {
resolve();
resolve(123);//这次调用无效
});// 2、获取成功失败结果
p.then(res => console.log(res), err => console.log(err));
Promise同步异步” />then的链式调用
const fs = require('fs');let p1 = new Promise((resolve, reject) => {fs.readFile('./a.txt', 'utf-8', (err, data) => {err ? reject(err) : resolve(data);})});let p2 = new Promise((resolve, reject) => {fs.readFile('./b.txt', 'utf-8', (err, data) => {err ? reject(err) : resolve(data);})});let p3 = new Promise((resolve, reject) => {fs.readFile('./c.txt', 'utf-8', (err, data) => {err ? reject(err) : resolve(data);})});//前一个then返回一个Promise对象//后一个then可以得到前一个Promise对象的成功状态的值p1.then(r1 => {console.log(r1); //aaareturn p2}).then(r2 => {console.log(r2); //bbbreturn p3;}).then(r3 => {console.log(r3); //ccc})const fs = require('fs');function myReadFile(filename) {return p = new Promise((resolve, reject) => {fs.readFile(filename, 'utf-8', (err, data) => {err ? reject(err) : resolve(data);})})}//前一个then返回一个Promise对象//后一个then可以得到前一个Promise对象的成功状态的值myReadFile('./a.txt').then(r1 => {console.log(r1); //aaareturn myReadFile('./b.txt');}).then(r2 => {console.log(r2); //bbbreturn myReadFile('./c.txt');}).then(r3 => {console.log(r3); //ccc})