厄运金字塔

时间:2015-06-30 03:56:32

标签: javascript node.js express q

我有这个路由代码到node.js表达应用程序,我尝试使用q来使用promises而不是进入" callback hell"。我包括一个"服务层"上面,需要进行两次调用,并返回一个包含两个函数数据的json结构。

var express = require('express');
var q = require('q');
var service = require('./../model/service');
var router = express.Router();

router.get('/trips', function(req, res, next) {
    service.getAllTrips(function(err, trips) {
        if (err) throw err;
        service.getPeopleForTrips(function(err, people) {
            if (err) throw err;
            var json = {
                trips: trips,
                people: people
            };
            return res.json(json);
        });
    });
});
module.exports = router;

我已尝试将两个服务调用分成q示例显示here,但仍然无法使其工作或如何构建此示例。感谢您的帮助。

这是我尝试过的:

q.fcall(service.getAllTrips)
    .then(service.getPeopleForTrips)
    .then(function (data1, data2) {
        console.log(data1);
        console.log(data2);
    })
    .catch(function (error) {
        console.log(error);
    })
    .done();

1 个答案:

答案 0 :(得分:1)

您可以将q.nfcall()用于以cb(err, result)格式进行回调的节点式函数。顺序形式:

var trips;
q.nfcall(service.getAllTrips)
.then(function(data){
    trips= data
    return q.nfcall(service.getPeopleForTrips)
})
.then(function (people) {
    console.log(trips, people);
})
.catch(function (error) {
    console.log(error);
})
.done();

使用q.all您可以并行运行promises数组,然后使用q.spread将返回的数组作为履行处理程序的参数进行传播:

q.all([
    q.nfcall(service.getAllTrips),
    q.nfcall(service.getPeopleForTrips)
]).spread(function(trips, people){
    console.log(trips, people);
})
.catch(function (error) {
    console.log(error);
})
.done();
相关问题