我所需要做的就是在当前函数执行结束时执行一个回调函数。
function LoadData()
{
alert('The data has been loaded');
//Call my callback with parameters. For example,
//callback(loadedData , currentObject);
}
这个函数的消费者应该是这样的:
object.LoadData(success);
function success(loadedData , currentObject)
{
//Todo: some action here
}
我怎么实现这个呢?
function callback(e){
return e;
}
var MyClass = {
method: function(args, callback){
console.log(args);
if(typeof callback == "function")
callback();
}
}
==============================================
MyClass.method("hello",function(){
console.log("world !");
});
==============================================
结果是:
hello world !
function login(email, password, callback) {
//verify the user
const users = [
{ email: "abc@gmail.com", password: "123" },
{ email: "xyz@gmail.com", password: "xyz" }
];
const user = users.find(
(user) => user.email === email && user.password === password
);
callback(user);
`enter code here`}
function redirect(user) {
if (user) {
//user is successfully logged in
console.log("user is successfully logged in ");
} else {
console.log("Incorrect credentials ");
}
}
login("abc@gmail.com", "123", redirect);
我希望这个例子能帮助所有想了解JS中回调的人
function callback(e){
return e;
}
var MyClass = {
method: function(args, callback){
console.log(args);
if(typeof callback == "function")
callback();
}
}
==============================================
MyClass.method("hello",function(){
console.log("world !");
});
==============================================
结果是:
hello world !