Promise介绍与基本使用
实例化Promise对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| const p = new Promise(function(resolve,reject){ setTimeout(function(){
let err='数据读取失败'; reject(err); },1000) });
p.then(function(value){ console.log(value); },function(reason){ console.error(reason); })
|
Promise封装读取文件
1.引入fs模块
const fs = require('fs');
2.调用方法读取文件
fs.readFile('文件路径',(err,data)=>{
if(err) throw err;
//如果没有出错,则输出内容
console.log(data.toString());
})
3.使用promise封装
const p = new Promise(function(resolve,reject){
fs.readFile("文件路径",(err,data)=>{
//判断是否失败
if(err) reject(err);
//如果成功
resolve(data);
})
})
p.then(function(value){
console.log(value.toString());
},function(reason){
console.log("读取失败!!");
});
Promise封装ajax请求
const p = new Promise(resolve,reject) = >{
//1.创建对象
const xhr = new XMLHttPRequest();
//2.初始化
xhr.open("GET","地址");
//3.发送
xhr.send();
//4.绑定事件,处理响应结果
xhr.onreadystatechange = function(){
//判断
if(xhr.readyState ===4){
//状态码
if(xhr.status>=200 &&xhr.status<300){
resolve(xhr.response);
}else{
reject(xhr.status);
}
}
}
}
p.then(function(value){
console.log(value);
},function(reason){
console.error(reason);
})
Promise.prototype.then方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| const p = new Promise((resolve,reject)=>{ setTimeout(()=>{ reject('出错啦'); },1000) });
const result = p.then(value = >{ console.log(value);
},reason=>{ console.warn(reason); }); console.log(result)
p.then(value=>{ }).then(value=>{ });
|
Promise实践练习-多个文件内容读取
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| const fs = require("fs"); fs.readFile('路径1',(err,data1)=>{ fs.readFile('路径2',(err,data2)=>{ fs.readFile('路径3',(err,data3)=>{ let result = data1 + '\r\n' +data2 +'\r\n' +data3; console.log(result); }); }); });
const p = new Promise((resolve,reject)=>{ fs.readFile('路径1',(err,data)=>{ resolve(data); }) }) p.then(value=>{ return new Promise((resolve,reject)=>{ fs.readFile('路径2',(err,data)=>{ resolve([value,data]); }); }) }).then(value =>{ return new Promise((resolve,reject)=>{ fs.readFile('路径3',(err,data)=>{ value.push(data); resolve(value); }); }) }).then(value =>{ console.log(value.join('\r\n')); })
|
Promise的catch方法
1 2 3 4 5 6 7 8 9 10 11 12
| const p = new Promise((resolve,reject)=>{ setTimeout(()=>{ reject('出错啦!'); },1000) }); p.then(function(value){},function(reason){ console.error(reason); });
p.catch(function(reason){ console.warn(reason); });
|