两种解决方案的现场演示here (click).
Promise 现在被认为是最好的方法,而不是回调。我将从回调开始,因为它们更容易上手并在之后讨论 Promise。
带有对象参数的基本回调:
//change this to true or false to make the function "succeed" or "fail"
//var flag = false;
var flag = true;
//this is the function that uses "success" and "error"
function foo(params) {
//some condition to determine success or failure
if (flag) {
//call the success function from the passed in object
params.success();
}
else {
//call the error function from the passed in object
params.error();
}
}
//function "foo" is called, passing in an object with success and error functions
foo({
success: function() {
console.log('success!');
},
error: function() {
console.log('error!');
}
});
确保在触发之前传入回调:
对于一个完整的解决方案,您还需要在调用它们之前确保这些属性存在 - 如果它们被传入,则仅调用成功和错误函数。
我会这样做:
if (flag) {
//the function is only fired if it exists
params.success && params.success();
}
作为单个参数传入的回调:
您不必在对象中传递它们。你可以让函数接受单个参数:
function foo(success, error) {
if (flag) {
success && success();
}
else {
error && error();
}
}
foo(
function() {
console.log('success!');
},
function() {
console.log('error!');
}
);
单独或在对象中传入的回调:
您还可以让函数根据传入的内容使用对象中的单个参数或函数。您只需检查第一个参数是函数还是对象并相应地使用它:
function foo(success, error) {
if (arguments.length === 1 && typeof arguments[0] === 'object') {
var params = arguments[0];
success = params.success;
error = params.error;
}
if(flag) {
success && success();
}
else {
error && error();
}
}
foo(function() {
console.log('success');
});
foo({
success: function() {
console.log('success!');
}
});
承诺!嘘!
正如我所说,我非常喜欢使用 Promise,它非常适合处理异步函数。这将需要一个 Promise 库或 ES6 JavaScript。这就是 jQuery 的样子。大多数库都是相似的:
function bar() {
var deferred = new $.Deferred();
if (flag) {
//if you resolve then, the first "then" function will fire
deferred.resolve();
}
else {
//if you reject it, the second "then" function will fire
deferred.reject();
}
return deferred.promise();
}
//since "bar" returns a promise, you can attach a "then" function to it
//the first function will fire when the promise is resolved
//the second function will fire when the promise is rejected
bar().then(function() {
console.log('bar success!');
},
function() {
console.log('bar error!');
});
使用 JavaScript ES6 承诺:
function bar() {
return new Promise(function(resolve, reject) {
if (flag) {
resolve()
}
else {
reject();
}
})
}
Promise 一开始可能很难理解。有很多很好的教程可以帮助你理解它们。