调用函数后的 JavaScript 回调

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4700424/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 14:34:34  来源:igfitidea点击:

JavaScript Callback after calling function

javascriptcallback

提问by ConnorLaCombe

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!

谢谢!

回答by Ivo Wetzel

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...

回答by Simon

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.

您可以添加一个 if 语句来检查您是否添加了回调函数。因此,您也可以在没有回调的情况下使用该函数。

function a(message, cb) {
    alert(message);
    if (typeof cb === "function") {
        cb();
    }
}

回答by ANAND SHULANOOR

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);
});