小编典典

无阻塞同步AJAX

ajax

有没有一种方法可以执行不冻结浏览器的同步AJAX查询?在我看来,在大多数情况下,同步请求要容易得多,但是它们阻止了代码其他部分的执行,这是一个真正的杀手。有没有办法获得同步AJAX而没有负面影响?(是的,我意识到术语“同步AJAX”是矛盾的。)


阅读 270

收藏
2020-07-26

共1个答案

小编典典

在即将到来的ECMAScript
2016(ES7)标准中,提供了一组新的语言关键字,这些关键字旨在执行与您似乎正在寻找的目标非常相似的操作,称为asyncawait

这些关键字 不会 允许“非阻塞同步AJAX”,但他们让你的方式,编写异步代码 看起来 同步。这是一个简单的例子:

// Let's say you have an asynchronous function that you want to call in a synchronous
// style...
function delayedEval(delay, func) {
  // First, ensure that the function returns a Promise object. If it doesn't, wrap it with
  // another function that does.
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve(func()), delay)
  })
  // For more on Promises, see https://goo.gl/uaoDuy (MDN link)
}

// Then, declare a function as asynchronous. This causes it to return a Promise that 
// resolves to its return value, instead of returning its return value directly.
async function delayedHello() {
  // Inside an async function, you can call other async functions like this, which looks
  // very much like a synchronous call (even though it isn't).
  let message = await delayedEval(1500, () => "Hello, world!")
  console.log(message)
}

// This returns (a Promise) immediately, but doesn't print "Hello, world!" until 1.5
// seconds later. (At which point it resolves the Promise.)
delayedHello()

尝试通天塔

基本上,而不是“无不良副作用同步AJAX”,asyncawait让你 异步 AJAX没有所有
负面影响。(具有许多用于处理回调的逻辑的混乱代码。)

async并且await是ES7标准中“异步功能”候选推荐的一部分。

2020-07-26