简体   繁体   中英

Node.js Q library: chain promise functions

First attempt at using node.js and making a controller. I'm using knex for the queries, and Q library for promises.

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.

The read function is from the route.

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 . 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

    }

    ...

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM