[英]Node.js Q library: chain promise functions
First attempt at using node.js and making a controller. 首先尝试使用node.js并使其成为控制器。 I'm using knex for the queries, and Q library for promises.
我正在使用knex进行查询,并使用Q库进行promise。
I'm trying to chain the async functions that query the DB but end up with an error here: 我试图链接查询数据库的异步函数,但最终在这里出现错误:
this.getPosts().then(this.getTags).then(function() ...
If I do only this.getPosts()
or only this.getTags()
, it correctly fetches them. 如果我只执行
this.getPosts()
或仅this.getTags()
,它将正确地获取它们。
The read
function is from the route. read
功能来自路由。
var db = require('../db');
var Q = require("q");
class IndexController {
constructor(page, data) {
this.page = page;
this.data = data;
}
getTags(){
var deferred = new Q.defer();
db('tags').select().then(function(tags){
this.data.tags = tags;
deferred.resolve();
}.bind(this));
return deferred.promise;
}
getPosts(){
var deferred = new Q.defer();
db('posts').select('*', 'posts.id as id', 'tags.name as tag')
.innerJoin('users', 'posts.user_id', 'users.id')
.leftJoin('post_tags', 'posts.id', 'post_tags.post_id')
.leftJoin('tags', 'post_tags.tag_id', 'tags.id')
.then(function(posts){
this.data.posts = posts;
deferred.resolve();
}.bind(this));
return deferred.promise;
}
read(res){ // <-- FROM ROUTE
this.getPosts().then(this.getTags).then(function(){
res.render(this.page, this.data);
}.bind(this));
}
...
}
knex is already using Promise so you don't have to use q
. knex已经在使用Promise了,所以您不必使用
q
。 Just return it. 只需退货即可。
var db = require('../db');
class IndexController {
constructor(page, data) {
this.page = page;
this.data = data;
}
getTags() {
return knex('tags').select().then(function(tags) {
this.data.tags = tags;
return tags
}
}
getPosts() {
return knex('posts').select('*', 'posts.id as id', 'tags.name as tag')
.innerJoin('users', 'posts.user_id', 'users.id')
.leftJoin('post_tags', 'posts.id', 'post_tags.post_id')
.leftJoin('tags', 'post_tags.tag_id', 'tags.id')
.then(function(posts) {
this.data.posts = posts;
return posts
}
}
read(res) { // <-- FROM ROUTE
}
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.