1.promisify
function toPrimisify (fn){
return function (...args){
return new Promise(function(resolve,reject){
fn(...args,function(err,data){
err?reject(err):resolve(data)
})
})
}
let read2 = toPrimisify(fs.readFile);
fs.readFile'./2.txt','utf8').then(res=>{console.log(res)});
2.promisifyAll
function toPromisifyAll(obj){
Object.keys(obj).forEach((item,index)=>{
if(typeof obj[item]=='function')
obj[item+'Async'] =toPrimisify(obj[item])
})
}
toPromisifyAll(fs);
fs.readFileAsync('./2.txt','utf8').then(res=>{console.log(res)});
3.promise.all
function promiseAll(promises){
return new Promise(function(resolve,reject){
if(!Array.isArray(promises)){
return reject(new TypeError("argument must be anarray"))
}
var countNum=0;
var promiseNum=promises.length;
var resolvedvalue=new Array(promiseNum);
for(var i=0;i<promiseNum;i++){
(function(i){
Promise.resolve(promises[i]).then(function(value){
countNum++;
resolvedvalue[i]=value;
if(countNum===promiseNum){
return resolve(resolvedvalue)
}
},function(reason){
return reject(reason)
)
})(i)
}
})
}
var p1=Promise.resolve(1),
p2=Promise.resolve(2),
p3=Promise.resolve(3);
promiseAll([p1,p2,p3]).then(function(value){
console.log(value)
})