小编noX*_*oXi的帖子

在onbeforeunload等待承诺

如果页面关闭,我想发送$ http.get.然后我找不到promises无法解决的问题,
因为如果最后一个方法返回,页面就会被销毁.

以下不起作用,因为onbeforeunload无法解析promises /不等待它们:

window.onbeforeunload = function(
    $http.get('http://someth.ing/update-state?page=unloaded').then(function(){
        // never called... never sent...
    }

}
Run Code Online (Sandbox Code Playgroud)

我知道,你可以使用默认的同步HTTP方法,但问题通常是我们如何同步/等待promises在这里解决.

我的想法是这样的:

window.onbeforeunload = function(){
    var ready = false;

    $http.get('http://someth.ing/update-state?page=unloaded').then(function(){
         ready=true;
    }

    // I don't see any other opportunity to sync a promise here than this:
    while(!ready) angular.noop();
    // big question: did $http call the server now? Can we finally return in this method to let the browser 'exit' the page?
}
Run Code Online (Sandbox Code Playgroud)

RFC

javascript synchronization onbeforeunload angularjs angular-promise

12
推荐指数
1
解决办法
3272
查看次数