[英]How to make a sync force in js?
I am writing a js lib, that consume services from a server (BE). 我正在写一个js库,它消耗服务器(BE)的服务。 I am using Jquery - AJAX to consume those services.
我正在使用Jquery-AJAX来使用那些服务。 However, to consume this server I need to set callback for success/error
但是,要使用此服务器,我需要为成功/错误设置回调
function CallAjax(callback){
$.ajax({
url: 'http://server.com/service1.svc',
success: function(data) {
callback(data);
}
});
}
So that I need to wait for the callback to return the proper value, but do function has already return to main page. 因此,我需要等待回调返回正确的值,但是do函数已经返回到主页。
myLib = (function () {
do = function ()
{
var callback = function() { return true };
CallAjax(callback);
}
}())
main page: but I want to consume the my lib sync but from the nature of the call I do not fin the way to make it. 主页:但是我想使用我的lib同步,但是从调用的性质来看,我没有找到实现它的方法。
I would like something like
if ( mylib.do() == true)
{ }
Any help? 有什么帮助吗?
You could set the async
switch to false. 您可以将
async
开关设置为false。 This will lead to a synchronous call to the server. 这将导致对服务器的同步调用。 Note though the consequences of this: the client browser will freeze during the execution of the request.
请注意,但这样做的后果是:客户端浏览器将在执行请求期间冻结。 If you don't want this to happen you will have to redesign your library so that it works with callbacks which IMHO is the correct way to work with AJAX.
如果您不希望发生这种情况,则必须重新设计您的库,以便它可与回调一起使用,而IMHO是使用AJAX的正确方法。 So provide callbacks to the consumer of your library.
因此,向您的库的使用者提供回调。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.