promise的使用
1.需求,有三个文件,异步读取,要求是按照顺序读取a.txt,b.txt,c.txt
第一步(定义函数)
封装一个函数(该函数需要传入一个路径,返回一个Promise)
function readFile(fPath){
return new Promise(
(resolve, reject)=>{
fs.readFile(fPath, 'utf-8', (err, dataStr) => {
if(err){
reject(err)
}else{
resolve(dataStr)
}
})
}
);
}
第二步(调用 在调用时,每次返回一个promise)
readFile('./files/file1.txt')
.then((value) => {
console.log(value);
return readFile('./files/file2.txt')
})
.then(function (data) {
console.log(data);
return readFile('./files/file31.txt')
})
.then(function (data) {
console.log(data);
})
可以对返回的调用使用catch捕获异常
2.在ajax中也可以使用promise
$("#ask").bind("click",function () {
$.ajax({
url: './data.json',
type: 'get',
dataType: 'json'
}).then(function(data){
console.log(data);
})
})