javascript - 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.
내가 뭘 잘못하고 있는 걸까? 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 프로미스 생성자는 resolve와 reject 함수를 매개변수로 받는 함수를 인자로 받습니다.
간단한 예:
let executor = (resolve, reject) => {
if(1>0) {
resolve("1");
} else {
reject("0");
};
let promise = new Promise<string>(executor);
