JavaScript Callback after calling function

2019-01-12 01:04发布

Ok so lets say I have this function:

function a(message) {
alert(message);
}

And I want to have a callback after the alert window is shown. Something like this:

a("Hi.", function() {});

I'm not sure how to have a callback inside of the function I call like that.

(I'm just using the alert window as an example)

Thanks!

3条回答
孤傲高冷的网名
2楼-- · 2019-01-12 01:24

There's no special syntax for callbacks, just pass the callback function and call it inside your function.

function a(message, cb) {
    console.log(message); // log to the console of recent Browsers
    cb();
}

a("Hi.", function() {
    console.log("After hi...");
});

Output:

Hi.
After hi...
查看更多
Deceive 欺骗
3楼-- · 2019-01-12 01:24

Here is the code that will alert first and then second. I hope this is what you asked.

function  basic(callback) {
    alert("first...");
    var a = "second...";
    callback(a);
} 

basic(function (abc) {
   alert(abc);
});
查看更多
贪生不怕死
4楼-- · 2019-01-12 01:45

You can add a if statement to check whether you add a callback function or not. So you can use the function also without a callback.

function a(message, cb) {
    alert(message);
    if (typeof cb === "function") {
        cb();
    }
}
查看更多
登录 后发表回答