打字稿从回调到功能

时间:2015-06-12 17:38:26

标签: mongodb typescript

我正在使用mongodb驱动程序来连接mongo:

 public listUsers(filterSurname?:string):any {

        if (this.connected) {
            debug.log(this.db);
            var results;
            this.db.collection('userProfiles').find({}).toArray((err:Error, res:any[])=> {
                if (err) return 'getting results error'
                else {
                    results=res;
                    results = res;
                }
                return res;
            });
        }
        debug.log('sending results' + results);
        if (results !== null) {

            return results;
        }
        else return 'connection error';
        return 'db unknown error'

    }

函数到数组有下一个签名:

toArray(callback: (err: Error, results: any[]) => any) : void;

我无法改变单一性,如何从回调函数返回值? 除了一次回调之外还有什么方法吗?或打字稿提供相同的回调地狱解决方案?

1 个答案:

答案 0 :(得分:0)

您要完成的是从异步进程(数据库查询)返回同步结果。

您需要实现处理异步结果的策略,以下是一些选项:

  

将回调函数传递给listUsers

public listUsers(filterSurname?:string, 
  callback: (err: Error, results: any[])=>void):any {
  if (this.connected) {
        debug.log(this.db);
        var results;
        this.db.collection('userProfiles').find({}).toArray(callback);
    }
    debug.log('sending results' + results);
    if (results !== null) {

        return results;
    }
    else return 'connection error';
    return 'db unknown error'

}
  

返回承诺

很少有承诺库,最受欢迎的是Qbluebird

以下是使用Q

的示例
 public listUsers(filterSurname?:string): Q.Promise<any[]> {
   var defer = Q.defer(); // create the promise structure
   if (this.connected) {
     debug.log(this.db);
     this.db.collection('userProfiles')
       .find({})
       .toArray((err:Error, res:any[])=> {
         if (err) {
           // reject the promise
           //     means something went wrong
           defer.reject('getting results error');
         } else {
           // resolve the promise
           //     means here is the result of what
           //     I promised I would give you
           defer.resolve(res);
         }
       });
   }
   return defer.promise; // return out the actual promise
 }