在即将到来的ECMAscript
2016(ES7)标准中,提供了一组新的语言关键字,这些关键字旨在执行与您似乎正在寻找的目标非常相似的操作,称为
async和
await。
这些关键字 不会 允许“非阻塞同步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”,
async并
await让你 异步 AJAX没有所有 的
负面影响。(具有许多用于处理回调的逻辑的混乱代码。)
async并且
await是ES7标准中“异步功能”候选推荐的一部分。



