Skip to content

Instantly share code, notes, and snippets.

@mcfog
Created March 13, 2017 05:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mcfog/99c6081194463b2c5591449dd2f8f3ef to your computer and use it in GitHub Desktop.
Save mcfog/99c6081194463b2c5591449dd2f8f3ef to your computer and use it in GitHub Desktop.
answer for promise paging exercise
//ref https://www.v2ex.com/t/346533#r_4122841
const api = (num) => {
const allNum = 3 + parseInt(7 * Math.random());//你不知到总页数的
const quality = 0.15;//接口质量指数
return new Promise((resolve, reject) => {
setTimeout(_=>{//超时逻辑
reject({
code: 'CODE_TIMEOUT',
msg: 'timeout'
})
}, 500);
//你不知道api到底会出什么错误,甚至可能直接永远没有结果
let problem = 0;
if(Math.random() < quality) {
problem = 10 * Math.random();
if(problem < 2) {
return;
}
}
setTimeout(() => {
if(problem > 0) {
if(problem < 5) {
return reject(new Error('some logic error'));
}
if(problem < 8) {
return reject({
randomStuff: Math.random()
});
}
return reject(null);
}
//返回结果模拟的有点小问题
if (num <= allNum) {
resolve([0,0,num]);//列表应该是多个值
} else {
resolve([]);//我说的API是返回空列表表示结束,不是false
}
}, 10)
})
}
const getList = (num = 1) => {
return api(num).then(null/*注意传null的行为*/, error => Promise.reject({/*封装错误*/
currentPage: num,
error
})
);
}
const getWholeList = (num = 1, list = []) => {
return getList(num).then(res => {
if(res.length == 0) {
return list;
}
return getWholeList(num + 1, [...list, ...res]);
}/*注意因为错误已经被getList封装了,此处无需处理*/);
}
getWholeList().then(res => {
console.log('完成', res);
}, e => {/*你的版本里的getWholeList并没有把错误体现到最终结果*/
console.error('失败', e);
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment