【问题标题】:typescript from callback back to function从回调返回到函数的打字稿
【发布时间】:2015-06-13 02:13:56
【问题描述】:

我正在使用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;

我无法更改签名,如何将值从回调返回给函数? 除了多一个回调,还有什么办法吗?还是 typescript 提供相同的回调地狱解决方案?

【问题讨论】:

  • 如果在 JS 中不能做某事,在 TS 中也不能做同样的事情。也许您应该将toArray 封装在一个承诺中。

标签: mongodb typescript


【解决方案1】:

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

您需要实施处理异步结果的策略,这里有几个选项:

将回调函数传入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'

}

返回一个承诺

目前很少有 Promise 库,最受欢迎的是 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
 }

【讨论】:

    猜你喜欢
    • 2021-12-08
    • 2020-08-27
    • 2020-04-24
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    • 1970-01-01
    • 2015-08-10
    • 1970-01-01
    相关资源
    最近更新 更多