- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我在异步函数中的 await 语句是对 jQuery 的 $.post() 方法的调用,该方法返回一个有效的 promise ,但是我在 TypeScript 中收到此错误:
Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member.
我的功能是这样的(为示例进行了简化)。该代码有效且有效,但我在 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.....');
}
}
我猜 TS 的 $.post() 有问题,因为你可以在上面调用 .then(),但我该如何解决这个问题?另外,我在更新 2.4.2 之前没有出现这个错误。
最佳答案
似乎 TypeScript 确实讨厌 jQuery 返回一个既是 a deferred and a jqXHR object 的 promise 对象:
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 object for more information).
对于 TypeScript 的这种顽固性,至少有三种解决方法
您可以将返回值传递给 Promise.resolve()
,这将返回一个真正的 ES6 Promise, promise 相同的值:
postResult = await Promise.resolve($.post(postUrl, $.param(postData)));
其他两个替代方案不返回纯 ES6 promise ,但 jQuery promise ,这仍然足够好。请注意,这些 promise 对象仅符合 Promises/A+ 标准 from jQuery 3 之后:
您可以应用 deferred.promise
method ,它返回一个 jQuery promise 对象:
postResult = await $.post(postUrl, $.param(postData)).promise();
或者,您可以应用 deferred.then
method ,它也会返回一个 jQuery promise:
As of jQuery 1.8, the
deferred.then()
method returns a new promise
通过不为 then
提供任何参数,您可以有效地返回相同 promise 值的 promise :
postResult = await $.post(postUrl, $.param(postData)).then();
关于jquery - 如何将 jQuery 的 $.post() 方法与 async/await 和 typescript 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45286834/
我是一名优秀的程序员,十分优秀!