微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在async / await和typescript中使用jQuery的$.post()方法

异步函数中的我的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

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();

原文地址:https://www.jb51.cc/java/121656.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐