加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 05:42:03 所属栏目:Java 来源:网络整理
导读:异步函数中的我的await语句是对jQuery的$.post()方法的调用,该方法返回一个有效的promise,但是我在TypeScript中遇到了这个错误: Type of ‘await’ operand must either be a valid promise or must not contain a callable ‘then’ member. 我的功能是这
异步函数中的我的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();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读