簡體   English   中英

Node.js Q庫:鏈承諾函數

[英]Node.js Q library: chain promise functions

首先嘗試使用node.js並使其成為控制器。 我正在使用knex進行查詢,並使用Q庫進行promise。

我試圖鏈接查詢數據庫的異步函數,但最終在這里出現錯誤:

this.getPosts().then(this.getTags).then(function() ...

如果我只執行this.getPosts()或僅this.getTags() ,它將正確地獲取它們。

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已經在使用Promise了,所以您不必使用q 只需退貨即可。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM