【Promise】Promise实现请求超时处理(加强版)

  昨天闲来无事,于是把之前写过的promise优化了一下,代码如下:

/*写文件、追加写、读文件*/
var fs = require('fs'); function wrapper(fn,context) {
var args = Array.prototype.slice.call(arguments,2);
return new Promise((resolve,reject) => {
args.push((err,data) => {
err ? reject(err) : resolve(data);
});
fn.apply(context,args);
});
} wrapper(fs.writeFile,fs,'message.txt','word')
.then(() => wrapper(fs.appendFile,fs,'message.txt','word'))
.then(() => wrapper(fs.readFile,fs,'message.txt','word'))
.then(data => console.log(data))
.catch(err => console.log(err)); /*获取员工id、并发获取两个接口信息、读信息*/
var http = require('http');
var url = require('url'); function delayPromise(ms) {
return new Promise((resolve,reject) => {
setTimeout(reject, ms);
});
} function get(url,ms) {
return new Promise.race([
delayPromise(ms),
wrapper(request,null,url).then(data => {
return JSON.parse(data);
})
]); } get('http://demos.so/result/homework.promise.userInfo')
.then( data => {
return Promise.all([get('http://demos.so/result/userid=' + args['_id']), get('http://demos.so/result/student=' + args['_id'])])
}
.then( data => console.log(data))
.catch( err => console.log(args));
上一篇:JS分割字符串并放入数组的函数


下一篇:[2019BUAA软工助教]第0次个人作业