厄运金字塔
Pyramid of doom
我有此路由代码到 node.js 快速应用程序,我正在尝试使用 q
来使用承诺而不是进入 "callback hell"。我在上面包含了一个 "service layer",需要进行两次调用,并且 return 一个包含来自两个函数的数据的 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();
您可以将 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
将返回的数组作为fulfillment handler的参数传播:
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();
我有此路由代码到 node.js 快速应用程序,我正在尝试使用 q
来使用承诺而不是进入 "callback hell"。我在上面包含了一个 "service layer",需要进行两次调用,并且 return 一个包含来自两个函数的数据的 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();
您可以将 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
将返回的数组作为fulfillment handler的参数传播:
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();