如何在 async/await 和 typescript 中使用 jQuery 的 $.post() 方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45286834/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use jQuery's $.post() method with async/await and typescript
提问by Amir
My await statements inside the async functions are calls to jQuery's $.post() method which return a valid promise, however I am getting this error in TypeScript:
我在异步函数中的 await 语句是对 jQuery 的 $.post() 方法的调用,它返回一个有效的承诺,但是我在 TypeScript 中遇到了这个错误:
Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member.
“await”操作数的类型必须是有效的 promise 或不能包含可调用的“then”成员。
My function is this (simplified for the example). The code is valid and works, but I am getting a error in the TS console.
我的功能是这个(为示例简化)。该代码有效且有效,但我在 TS 控制台中收到错误消息。
async function doAsyncPost() {
const postUrl = 'some/url/';
const postData = {name: 'foo', value: 'bar'};
let postResult;
let upateResult;
function failed(message: string, body?: string) {
console.log('error: ', message, ' body: ', body);
}
function promiseFunc() {
return new Promise<void>( resolve => {
// ... do something else....
resolve();
});
};
function finish() {
// ... do something at the end...
}
try {
// The error is on the $.post()
postResult = await $.post(postUrl, $.param(postData));
if (postResult.success !== 'true') {
return failed('Error as occoured', 'Description.....');
}
await promiseFunc();
return finish();
} catch (e) {
await failed('Error as occoured', 'Description.....');
}
}
I'm guessing TS is having a problem with $.post() because you can call .then() on it, but how do I get around this problem? Also, I did not have this error prior to updating 2.4.2.
我猜 TS 对 $.post() 有问题,因为你可以在它上面调用 .then(),但我如何解决这个问题?另外,我在更新 2.4.2 之前没有这个错误。
回答by trincot
Seems indeed TypeScript is pesky about jQuery returning a promise object which is both a deferred and a jqXHR object:
似乎 TypeScript 很讨厌 jQuery 返回一个既是延迟对象又是jqXHR 对象的承诺对象:
The jqXHR objects returned by
$.ajax()
as of jQuery 1.5 implement the Promise interface, giving them all the properties, methods, and behavior of a Promise (see Deferred objectfor more information).
从
$.ajax()
jQuery 1.5 开始返回的 jqXHR 对象实现了 Promise 接口,为它们提供了 Promise 的所有属性、方法和行为(有关更多信息,请参阅延迟对象)。
There are at least three workarounds to this stubbornness of TypeScript
至少有三种解决方法可以解决 TypeScript 的这种顽固性
Solution returning a pure ES6 Promise
返回纯 ES6 Promise 的解决方案
You could pass the return value to Promise.resolve()
, which will return a true ES6 Promise, promising the same value:
您可以将返回值传递给Promise.resolve()
,这将返回一个真正的 ES6 Promise,承诺相同的值:
postResult = await Promise.resolve($.post(postUrl, $.param(postData)));
Solutions returning jQuery promises
返回 jQuery 承诺的解决方案
The other two alternatives do not return pure ES6 promises, but jQuery promises, which still is good enough. Be aware though that these promise objects are only Promises/A+ compliant from jQuery 3onwards:
其他两种选择不返回纯 ES6 承诺,而是 jQuery 承诺,这仍然足够好。请注意,这些承诺对象仅从jQuery 3开始符合 Promises/A+ 标准:
You could apply the deferred.promise
method, which returns a jQuery promise object:
您可以应用该deferred.promise
方法,该方法返回一个 jQuery 承诺对象:
postResult = await $.post(postUrl, $.param(postData)).promise();
Alternatively, you could apply the deferred.then
method, which also returns a jQuery promise:
或者,您可以应用该deferred.then
方法,该方法也返回一个 jQuery 承诺:
As of jQuery 1.8, the
deferred.then()
method returns a new promise
从 jQuery 1.8 开始,该
deferred.then()
方法返回一个新的承诺
By not providing any argument to then
you effectively return a promise for the same promised value:
通过不向then
您提供任何参数,有效地返回具有相同承诺值的承诺:
postResult = await $.post(postUrl, $.param(postData)).then();
回答by libertyernie
JQueryXHR has its own version of .then() which has some additional options:
JQueryXHR 有自己的 .then() 版本,它有一些额外的选项:
then<R>(doneCallback: (data: any, textStatus: string, jqXHR: JQueryXHR) => R, failCallback?: (jqXHR: JQueryXHR, textStatus: string, errorThrown: any) => void): JQueryPromise<R>;
To use await in TypeScript with $.post, I had to remove that line from jquery.d.ts. TypeScript will then see the .then defined on JQueryGenericPromise.
要在带有 $.post 的 TypeScript 中使用 await,我必须从 jquery.d.ts 中删除该行。然后,TypeScript 将看到 JQueryGenericPromise 上定义的 .then。