[英]This does not seem to be returning the correct object (Typescript)
我創建了一個小類,該類包裝了通用回調函數簽名,並返回了Promise。
但是,然后它將句柄稱為_resolve未定義。
/// <reference path="typings/es6-promise/es6-promise.d.ts" />
import rsvp = require('es6-promise');
var Promise = rsvp.Promise;
/** * wrapper a callback style call into a promise */ class
Promiseify<T> {
private _promise : Promise<T>;
private _resolve : (result?: T) => void;
private _reject : (error: any) => void;
/**
* create wrapper, example: new Promiseify(call).promise
* @param call example (handle) => yourDb.update(document, handle)
*/
constructor(call:(handle:(error: any, result: T) => void) => void){
this._promise = new Promise<T>((resolve, reject) =>{
this._resolve = resolve;
this._reject = reject;
call(this.handle);
});
}
handle(error: any, result: T) {
if(error != null) this._reject(error);
else this._resolve(result);
}
/**
* get the es6 promise which can then be passed to external callers
* @returns {Promise<T>} the es6 promise which this class creates.
*/
get promise() : Promise<T>{
return this._promise;
}
}
//the test rig
new Promiseify<string>((handle)=> {
handle(null, 'hello world');
}).promise.then((greeting: string)=> {
console.log(greeting);
});
我是否缺少任何東西,順便說一句幕后的JS看起來也不錯
也可以幫助我在Webstorm 9.03內部的Node.JS上運行它
您正在將this.handle
傳遞給call()
,所以當call()
調用它時, this
將為null
,這就是您的方法不起作用的原因。
我不確定TypeScript中最慣用的是什么,但是您可以這樣做:
call(this.handle.bind(this));
要么
call((error, result) => this.handle(error, result));
或者,您可以完全擺脫handle
方法,並執行以下操作:
this._promise = new Promise<T>((resolve, reject) => {
call(function (error, result) {
if (error) { reject(error); }
resolve(result);
});
});
但這只剩下一個問題,為什么當您可以使用執行相同功能的8行函數時,為什么根本需要一個類:
function promisify<T>(call:(handle:(error: any, result :T) => void) => void) {
return new Promise<T>((resolve, reject) => {
call(function (error, result) {
if (error) { reject(error); }
resolve(result);
});
});
}
您在這里有兩個選擇:
第一個是將handle方法聲明為屬性,如下所示:
handle = (error: any, result: T) => {
if(error != null) this._reject(error);
else this._resolve(result);
}
或更改您的調用方法,使其在實例上調用它,如下所示:
var that = this;
call(function(e, r) { that.handle(e, r); });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.