如何在nodejs中处理Promise

时间:2017-03-06 09:24:10

标签: mysql node.js angular express

我正在尝试使用expressjs和angular 2在nodejs中执行回调函数(我不知道它是否与angular2部分相关)。

我的工作是: 我在angular2中有一个公式,我向我的API路由发送一个get请求,然后我通过get将表单中的文本字段发送到URL,然后我做一个MYSQL查询来查看电话簿数据库,我'我期望从电话簿中获得一个完整的用户详细信息。

表现公式:

<div class="container">
<div class="col-md-4">
<h1>Addressbook</h1>
<form [formGroup]="searchForm" (ngSubmit)="doSearch($event)">
<input formControlName="searchString" type="text" placeholder="Name">
<button type="submit">Search</button>
</form>
</div>
</div>

第一个功能,doSearch:

doSearch(event) {
    let formData = this.searchForm.value;
    var searchString = this.searchForm.value.searchString;

    this.http.get('/phonebook/search/'+searchString, function(req, res){}).subscribe(
    function(response) {
    console.log("Success Response");
    },
    function(error) { console.log("Error happened" + error)},
    function() { console.log("the subscription is completed")}
    );
}

这会调用发送参数的路由,所以不那么难。

现在创建路由器进入游戏:

public static create(router: Router, basePath: string) {
    console.log("[SearchRoute::create] Creating routes for /search.");
    // call the function for retrieving the address book results
    router.get(basePath + "/search/:searchString", (req: Request, res: Response, next: NextFunction) => {
    console.log("##  [SearchRoute] Called GET /search.");
    var object = searchUser(req);
    console.log(object);
        });
}

最后,函数searchUser被调用:

function searchUser(req: Request) {

    console.log("searchUser Function executed.");

    var searchString = req.params.searchString;

    var query = p_query('SELECT XXXX')
    .then(function (results) {
    console.log("query executed and all okay");
    return (results);
    })
    .catch(function (error) {
    console.error("Wooopsi", error);
    });

    console.log("query result: "+query);
}

另外,我在这里发布了我构建的新查询函数,以便能够处理promises(我不知道它是否是最佳选择):

function p_query(q) {
    return new Promise(function (resolve, reject) {
    // The Promise constructor should catch any errors thrown on
    // this tick. Alternately, try/catch and reject(err) on catch.
    myMYSQL.db.query(
    q,
    function (error, results) {
    if (error)
    reject(error);
    resolve(results);
    });
    })
};

那么,我真正想做的是什么,我的问题是什么?

我想将查询结果发送回客户端(angular2公式),我无法做到......

所以在这篇很长的帖子之后,如果你读到这里,我真的很感激,并为这个复杂的问题感到抱歉!

PS:我知道我解释自己非常糟糕:(

此致 丹尼尔

3 个答案:

答案 0 :(得分:0)

你应该使用递归回调与每个查询结果尝试享受异步平台的美感。 通过

将数据发送到客户端
res.send(data);

答案 1 :(得分:0)

在这个official angular 2 documentation on the http client中,他们建议将http逻辑放入一个单独的服务中。我已经将它设置为类似于search.service.ts的示例:

import { Injectable } from '@angular/core';
import { Http, Response,Headers, RequestOptions,URLSearchParams }
          from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

@Injectable()
export class SearchService {
    constructor(private http: Http) { 
    }

    getSearchResult(searchString)  : Observable<any>  {
        return this.http.get('/phonebook/search/'+searchString)
         .map(this.extractData)
         .catch(this.handleError);
    }

    private extractData(res: Response) {
        let body = res.json();
        return body;
    }
    private handleError (error: Response | any) {
        let errMsg: string;
        if (error instanceof Response) {
            const body = error.json() || '';
            const err = body.error || JSON.stringify(body);
            errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
        } else {
            errMsg = error.message ? error.message : error.toString();
        }
        return Observable.throw(errMsg);
    }
}

在您的组件中导入服务并执行代码段:

// don't forget to put the service in the app.modul or the component providers!
  constructur(public mySearchService : SearchService) {}

// in your doSearch of your component:
   doSearch(event) {
    let formData = this.searchForm.value;
    var searchString = this.searchForm.value.searchString;
    mySearchService.getSearchResult(searchString).subscribe(
        data => mylist.data, // or which datastructure I want to write to.
        error => console.error(error) // or how I log the errors..
    );
   }

编辑:数据库模型中的search_user:

function searchUser(searchString) {
   console.log("searchUser Function executed.");
   return myMYSQL.db.select('phonebookentry', {
        pbe_lastname: searchString, pbe_syncstate: 'new'
   }) // returning the promise/observable to the main function...
} // Currently I don't know, how the returned data looks like.

the router的节点/快速方面,发送res.json 编辑:使用异步调用searchUser

router.get(basePath + "/search/:searchString", 
    (req: Request, res: Response, next: NextFunction) => {
    console.log("##  [SearchRoute] Called GET /search.");
    searchUser(req)
     .then( data => res.json(data);console.log(data) )
     .catch (error => console.log(error));
    });

答案 2 :(得分:0)

你的答案完全是完美的,我理解一切!我现在面临的唯一问题,就是这个问题:

我正在调用函数searchUser,并且它不会返回任何内容,只是一个未定义的对象,所以我知道我没有正确地返回。

那是我的searchUser函数:

function searchUser(searchString) {

console.log("searchUser Function executed.");

myMYSQL.db.select('phonebookentry', {
pbe_lastname: searchString,
pbe_syncstate: 'new'
}).then(function (user) {
console.log("user before: "+user);
return (user);
}).catch(function (err) {
console.log(err);
})}

非常感谢你的有用答案!我快要完蛋了