How to use $. Of jQuery in async / await and typescript Post() method
My await statement in the asynchronous function is $. For jQuery Call of post() method, which returns a valid promise, but I encountered this error in typescript:
My function is this (example simplification) The code is valid and valid, but I received an error in the TS console
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 guess TS has $ Post () because you can call Then (), but how to solve this problem? In addition, in update 2.4 I didn't make this error before 2
Solution
It seems that typescript is wrong for jQuery to return a declaration object, which is a delayed and a jqxhr object:
There are at least three solutions to this obstinacy of typescript
Solution returns pure ES6 promise
You can pass the return value to promise Resolve(), which will return a true ES6 promise, promising the same value:
postResult = await Promise.resolve($.post(postUrl,$.param(postData)));
Return the solution promised by jquery
The other two options will not return the pure ES6 commitment, but the jQuery commitment is still good enough Please note that although these commitment objects are only promise / a compatible from jQuery 3:
You can apply deferred Promise method, which returns a jQuery promise object:
postResult = await $.post(postUrl,$.param(postData)).promise();
Alternatively, you can apply deferred Then method, which also returns a jQuery commitment:
By not providing any parameters, you can effectively return commitments with the same commitment value:
postResult = await $.post(postUrl,$.param(postData)).then();