【问题标题】:TypeScript es6-promise, how do I match Promise constructorTypeScript es6-promise,我如何匹配 Promise 构造函数
【发布时间】:2015-12-28 07:30:00
【问题描述】:

试试这个:

  init():Promise<mongodb.Db> {
    return new Promise<mongodb.Db>((resolve : (value?: R | Thenable<R>) => void, reject: (error?: any) => void) => {
      this.db = new mongodb.Db("test", new mongodb.Server("localhost", 12017));

      this.db.open((err, db) => {
        if (err) {
          reject(err);
        } else {
          resolve(db);
        }
      });
    });
  }

给我这个:

error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature.

我做错了什么?我直接从 Promise 的类定义中复制了构造函数参数。尝试了很多很多不同的方法来做到这一点,但都没有奏效。显然,因此问题:)

【问题讨论】:

    标签: javascript node.js typescript es6-promise


    【解决方案1】:

    不知道你从哪里得到这个定义。 你的编译器目标设置为 es6 吗?

    来自lib.es6.d.ts

    /**
     * Creates a new Promise.
     * @param executor A callback used to initialize the promise. This callback is passed two arguments: 
     * a resolve callback used resolve the promise with a value or the result of another promise, 
     * and a reject callback used to reject the promise with a provided reason or error.
     */
    new <T>(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void): Promise<T>;
    

    对我来说很好用 typescript 1.7.5,目标 es6

    这应该适合你

    return new Promise<mongodb.Db>((resolve: (value?: any) => void, reject: (reason?: any) => void) => {
    ...
     })
    

    【讨论】:

      【解决方案2】:

      ES6 Promise 构造函数接受一个函数,该函数将解析和拒绝函数作为参数。

      一个简单的例子:

      let executor = (resolve, reject) => {
         if(1>0) {
            resolve("1");
         } else {
            reject("0");
         };
      
      let promise = new Promise<string>(executor);
      

      【讨论】:

      • 抱歉,这不起作用。由于某种原因,没有找到构造函数。我的目标是模块 commonjs 和 es5,因为我希望它在 NodeJS 中工作。
      • 这是 ES6 的承诺,如果你使用的是 es5,你很可能使用的是第三方承诺库。他们通常遵循相同的风格,但可能存在差异。请分享您正在使用的承诺库。
      猜你喜欢
      • 1970-01-01
      • 2020-08-20
      • 2020-06-10
      • 2013-01-06
      • 2015-07-14
      • 1970-01-01
      • 1970-01-01
      • 2023-01-18
      • 1970-01-01
      相关资源
      最近更新 更多