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之前,我没有此错误.
解决方法
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 07001 for more information).
TypeScript的这种顽固性至少有三种解决方法
解决方案返回纯ES6 Promise
您可以将返回值传递给Promise.resolve()
,这将返回一个真正的ES6 Promise,承诺相同的值:
postResult = await Promise.resolve($.post(postUrl,$.param(postData)));
返回jQuery承诺的解决方案
另外两个选择不会返回纯ES6承诺,但jQuery承诺,仍然足够好.请注意,虽然这些承诺对象只是Promise / A兼容from jQuery 3以后:
您可以应用deferred.promise
method,它返回一个jQuery promise对象:
postResult = await $.post(postUrl,$.param(postData)).promise();
或者,你可以应用deferred.then
method,它也返回一个jQuery承诺:
As of jQuery 1.8,the
deferred.then()
method returns a new promise
通过不提供任何参数,您可以有效地返回相同承诺值的承诺:
postResult = await $.post(postUrl,$.param(postData)).then();