Last active
December 13, 2016 02:37
-
-
Save yangfch3/4b1b4dab90c2488d9e32735ae18df185 to your computer and use it in GitHub Desktop.
模拟一个异步 API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 模仿一个需要耗时 2000ms 的异步 API:asyncOp | |
const asyncOp = function(a, b, callback) { | |
try { | |
// 这里是可能出现输出 error 的操作 | |
if (typeof a !== 'number' || typeof b !== 'number') { | |
let err = new Error('asyncOp(): 前两个参数必须为数值'); | |
err.type = 1; | |
throw err; | |
} | |
if (typeof callback !== 'function') { | |
let err = new Error('asyncOp(): 请传入回调函数作为第三个参数'); | |
err.type = 2; | |
throw err; | |
} | |
let total = a + b; | |
// 没有出现错误时,为回调函数传入的 err 为 undefined | |
setTimeout(function() { | |
callback(undefined, total); | |
return total; | |
}, 2000); | |
} catch(err) { | |
if (err.type === 1) { | |
callback(err, total); | |
return err; | |
} else if (err.type === 2) { | |
console.log(err.message); | |
return err; | |
} | |
} | |
}; | |
// 下面是简单的使用 | |
// 创建一个回调函数 | |
// let print = function(err, data) { | |
// if (err) { | |
// console.error(err.message); | |
// } else { | |
// console.log(data); | |
// } | |
// } | |
// asyncOp(1, 1, print); | |
// asyncOp('a', 'b', print); | |
// console.log('Hello World!'); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment