How to use jQuery's $.post() method with async/await and typescript

前端 未结 2 1207
无人共我
无人共我 2020-12-15 21:51

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:

相关标签:
2条回答
  • 2020-12-15 22:24

    Seems indeed TypeScript is pesky about jQuery returning a promise object which is both a deferred and a jqXHR object:

    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).

    There are at least three workarounds to this stubbornness of TypeScript

    Solution returning a pure ES6 Promise

    You could 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)));
    

    Solutions returning jQuery promises

    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 3 onwards:

    You could apply the deferred.promise method, which returns a jQuery promise object:

    postResult = await $.post(postUrl, $.param(postData)).promise();
    

    Alternatively, you could apply the deferred.then method, which also returns a jQuery promise:

    As of jQuery 1.8, the deferred.then() method returns a new promise

    By not providing any argument to then you effectively return a promise for the same promised value:

    postResult = await $.post(postUrl, $.param(postData)).then();
    
    0 讨论(0)
  • 2020-12-15 22:26

    JQueryXHR has its own version of .then() which has some additional options:

    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.

    0 讨论(0)
提交回复
热议问题