当ajax请求时等待jQuery. [英] await for jQuery.when ajax requests

查看:63
本文介绍了当ajax请求时等待jQuery.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

异步函数中的此代码未提供预期的结果:

This code inside async function, does not give the expected result:

var result = await $.when( $.get('/api/1'), $.get('/api/2') );

一个请求,结果将是我期望的输出(响应文本).但是,对于这两个请求,返回的 result 是一个不包含两个Promises值的数组.有什么解决方法吗?
我知道有 then() done(),但是我更喜欢使用await.

with one request, result will be the output I expect (the response text). However, with these two requests, the returned result is an array which does not hold the two Promises values. Is there any workaround?
I know there are then() and done(), but I prefer using await.

推荐答案

jQuery的 .when()和本机的 await 具有不同的语义.比较:

jQuery's .when() and the native await have different semantics. Compare:

// jQuery

$.when(promise1, promise2).done(function (result1, result2) {
    // work with result1 and result2
});

// native

Promise.all([promise1, promise2]).then(function (results) {
    // work with results[0] and results[1]
});

// await is just a variation of the above:

var results = await Promise.all([promise1, promise2]);
// work with results[0] and results[1]

本机实现使用包含多个promise的单个数组,而jQuery的实现则期望多个单独的promise.

The native implementation uses a single array of multiple promises, while jQuery's implementation expects multiple individual promises.

这意味着您不能将 await $.when()一起使用.当异步函数完成时, await 有效地为您提供回调的 first 参数值.

This means that you can't use await with $.when(). await effectively gives you the value of the first argument to the callback when the asynchronous function completes.

await 用于 Promise.all()是可行的,因为第一个参数将是所有结果的数组.对 $.when()使用 await 无效,因为第二个结果将是回调的第二个参数,依此类推,这意味着您将丢失所有除第一个以外的结果.

Using await for Promise.all() works, because the first argument will be an array of all results. Using await for $.when() won't work, because the second result will be the second argument to the callback, and so on, which means you would lose all results except the first one.

jQuery的实现早于原生的Promise,他们以这种方式设计了它,现在必须坚持下去.这就是生活.

jQuery's implementation predates native promises, they designed it this way and now they have to stick with it. Such is life.

这篇关于当ajax请求时等待jQuery.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆