ajax 同步deprecated,ajax - Synchronous XMLHttpRequest deprecated - Stack Overflow

This answer has been edited.

Short answer:

They don't want sync on the main thread.

The solution is simple for new browsers that support threads/web workers:

var foo = new Worker("scriptWithSyncRequests.js")

Neither DOM nor global vairables aren't going to be visible within a worker but encapsulation of multiple synchronous requests is going to be really easy.

Alternative solution is to switch to async but to use browser localStorage along with JSON.stringify as a medium. You might be able to mock localStorage if you allowed to do some IO.

http://caniuse.com/#search=localstorage

Just for fun, there are alternative hacks if we want to restrict our self using only sync:

It is tempting to use setTimeout because one might think it is a good way to encapsulate synchronous requests together. Sadly, there is a gotcha. Async in javascript doesn't mean it gets to run in its own thread. Async is likely postponing the call, waiting for others to finish. Lucky for us there is light at the end of the tunnel because it is likely you can use xhttp.timeout along with xhttp.ontimeout to recover. See Timeout XMLHttpRequest

This means we can implement tiny version of a schedular that handles failed request and allocates time to try again or report error.

// The basic idea.

function runSchedular(s)

{

setTimeout(function() {

if (s.ptr < callQueue.length) {

// Handles rescheduling if needed by pushing the que.

// Remember to set time for xhttp.timeout.

// Use xhttp.ontimeout to set default return value for failure.

// The pushed function might do something like: (in pesudo)

// if !d1

// d1 = get(http...?query);

// if !d2

// d2 = get(http...?query);

// if (!d1) {pushQue tryAgainLater}

// if (!d2) {pushQue tryAgainLater}

// if (d1 && d2) {pushQue handleData}

s = s.callQueue[s.ptr++](s);

} else {

// Clear the que when there is nothing more to do.

s.ptr = 0;

s.callQueue = [];

// You could implement an idle counter and increase this value to free

// CPU time.

s.t = 200;

}

runSchedular(s);

}, s.t);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值