javascript 在Javascript中的return语句之后执行语句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14102912/
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-26 20:42:54  来源:igfitidea点击:

Execute statement after return statement in Javascript

javascriptjqueryhtmldom-events

提问by Faisal Amjad

window.onbeforeunload = function() {
    if (document.getElementById("parentpan").style.display == "block") {
        return "You are logged out.";
            Logout();
    }
};

I want the logout()function to be called after the return statement, is it possible?

我希望在logout()return 语句之后调用该函数,这可能吗?

回答by Femaref

You can't execute anything after a return statement.

在 return 语句之后不能执行任何操作。

edit: the finallystatement allows code execution after a returnfor cleanup purposes.

编辑:该finally语句允许在 a 之后执行代码以return进行清理。

(This is a good example for an XY-Question: You are asking about Y while never telling us for what X you actually need it).

(这是 XY 问题的一个很好的例子:您在询问 Y 而从不告诉我们您实际需要什么 X)。

回答by sgrif

The return statement ends a function, you cannot execute code after it. You could do this:

return 语句结束一个函数,你不能在它之后执行代码。你可以这样做:

ret = "You are logged out.";
Logout();
return ret;

回答by Aadit M Shah

What you need is to execute Logoutasynchronously. This can be easily achieve in JavaScript by using the setTimeoutfunction as others have said. Here's a method I commonly use to call functions asynchronously:

您需要的是Logout异步执行。这可以通过使用setTimeout其他人所说的函数在 JavaScript 中轻松实现。这是我常用的异步调用函数的方法:

Function.prototype.async = function () {
    setTimeout.bind(null, this, 0).apply(null, arguments);
};

This method pushes a function call onto the event loop immediately (after 0ms). Hence the function is executed after the current code completes (which for you is after you return). Here's a simple example of how to use it:

此方法立即(在0ms之后)将函数调用推送到事件循环中。因此该函数在当前代码完成后执行(对你来说是在你返回之后)。这是一个如何使用它的简单示例:

alert.async("This will be displayed later.");
alert("This will be displayed first.");

Since the first alertis called asynchronously it will execute after the second call to alert. As simple as preceding your function call with async. This is what you would do in your case:

由于第一个alert是异步调用的,它将在第二个调用之后执行alert。就像在函数调用之前使用async. 这就是你在你的情况下会做的:

window.onbeforeunload = function () {
    if (document.getElementById("parentpan").style.display === "block") {
        Logout.async();
        return "You are logged out.";
    }
};

What's the disadvantage? Since the function is blocked on the event loop it may never get the chance to execute (hence the user will never logout). Such a situation mayarise. It usually occurs when the control goes into an infinite loop, or hangs because of a blocking AJAX request.

有什么缺点?由于该函数在事件循环中被阻塞,它可能永远没有机会执行(因此用户永远不会注销)。可能会出现这样的情况。它通常发生在控件进入无限循环或由于阻塞 AJAX 请求而挂起时。

Good news for you however, this happens on a veryrare occasion. So don't worry about it. Just use setTimeoutlike everyone else is bantering you to and you'll do just fine. Personally I think you should log out before returning a message that "You are logged out.", but it's your application.

不过,这对您来说是个好消息,这种情况发生在非常罕见的情况下。所以不用担心。就像setTimeout其他人开玩笑一样使用,你会做得很好。我个人认为您应该在返回消息之前注销"You are logged out.",但这是您的应用程序。

Happy New Year. Cheers!

新年快乐。干杯!

回答by bhavsar japan

The best possible way and most efficient way is **try , catch and finally **

最好的方法和最有效的方法是 **try , catch 和 finally **

catch is optional in this

catch 是可选的

 `try{ 
     // do something
     return;
   } finally {
    // call function after return
   }`

https://youtu.be/Is_o_L-ZIS8this is helpful for you

https://youtu.be/Is_o_L-ZIS8这对你有帮助

回答by epascarello

Most of the other answerers are missing what you are trying to do here. You want window.onbeforeunloadto act like window.confirm(). There is no way to act on the ok action in the onbeforeunload event.

大多数其他回答者都错过了您在这里尝试做的事情。你想表现window.onbeforeunload得像window.confirm(). 没有办法对 onbeforeunload 事件中的 ok 动作采取行动。

What you would have to do is hook it up on onunload to do the action.

您需要做的是将其连接到 onunload 上以执行操作。

window.onbeforeunload = function () { 
    return "Your session will be logged out" 
};
window.onunload = function () { 
    logout(); 
}

Problem with this is modern day browsers will kill a lot of processes that run in unload/beforeunload to "speed up" the browser so it is faster. So if it is asynchronous, you will have a race condition.

问题是现代浏览器会杀死许多在卸载/卸载之前运行的进程,以“加速”浏览器,使其更快。因此,如果它是异步的,则会出现竞争条件。

回答by Stuart

In general if you want something to be executed after the function has returned, you can set a timer:

通常,如果您希望在函数返回后执行某些操作,您可以设置一个计时器:

function myFunction() {
    if (document.getElementById("parentpan").style.display == "block") {
        setTimeout(Logout, 50); // Logout will be called 50ms later
        return "You are logged out.";
    }
};

However, as noted in comments, this is not a good idea for onbeforeunload, as the timer event will not be fired if the page finished unloading first.

但是,正如评论中所指出的,这对于 onbeforeunload 来说不是一个好主意,因为如果页面先完成卸载,则不会触发计时器事件。

回答by Luffy

If you have jquery in your project you can use defered mechanism. You can return promise object for ongoing tasks like this :

如果您的项目中有 jquery,您可以使用延迟机制。您可以为正在进行的任务返回 promise 对象,如下所示:

function task() {

   var defered = $.Deferred();
   setTimeout(defered.resolve , 5000);
   return defered.promise();

}  

function task2() {

   var defered = $.Deferred();
   setTimeout(defered.resolve , 10000);
   return defered.promise();
}   

function run() {
     return $.when(task(),task2());
}

var promise = run();

promise.done(function(){        
      alert("All tasks has been completed");        
});

Demo

演示

回答by Imamudin Naseem

You can use setTimeoutto achieve this. Your code should be as below

您可以使用它setTimeout来实现这一点。您的代码应如下所示

window.onbeforeunload = function() {
    if (document.getElementById("parentpan").style.display == "block") {
        setTimeout(function(){
            Logout();
        }, 0);
        return "You are logged out.";
    }
};

This will make sure that Logoutis executed after return statement.

这将确保Logout在 return 语句之后执行。

回答by Ankit Bhagat

    var a = 10;
function b(){
    a = 25;
  return;
    function a(){}
}
b();
document.write(a);

try it

试试看

回答by Renjith

return means you are returning from the execution of the called function.When return statement is executed, system understands that the function execution is over and it will switch to the main program from which the function is called.

return 表示你正在从被调用函数的执行中返回。当 return 语句被执行时,系统知道函数执行结束,它会切换到调用函数的主程序。

In the program, you can see a statement after return.But the system wont check that even.

在程序中,你可以看到return后的语句。但是系统甚至不会检查。