TypeScript es6-promise,我如何匹配Promise构造函数
尝试这个:
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.
我究竟做错了什么? 构造函数参数I直接从Promise的类定义中复制而来。 尝试了许多不同的方法来做到这一点,但他们都没有工作。 显然,因此这个问题:)
不知道你从哪里得到这个定义。 你的编译器目标是否设置为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>;
对我打字稿1.7.5,目标es6罚款
这应该适合你
return new Promise<mongodb.Db>((resolve: (value?: any) => void, reject: (reason?: any) => void) => { ... })
ES6承诺构造函数接受一个函数,它将parsing和拒绝函数作为参数。
一个简单的例子:
let executor = (resolve, reject) => { if(1>0) { resolve("1"); } else { reject("0"); }; let promise = new Promise<string>(executor);