2015-05-07 44 views
0

我正在開發一個應用程序的NodeJS並有一個函數用於出口,像這樣:通行證回調的NodeJS查看

module.exports = { 
    userCount: function(done) { 
    user.count(function(err, count) { 
     done(count); 
    }); 
    } 
} 

我試圖做的是回調傳遞給視圖。這是我當前如何做:

methods.userCount(function(count) { 
    app.get("/", function(req, res) { 
    res.render("../views/index", { 
     userCount: count 
    }); 
    }); 
}); 

這工作正常,但我的問題是會有被導出多種功能,因此,我將需要多個回調,傳遞給了同樣的觀點。

我現在正在將它作爲將回調傳遞給視圖的最佳方式嗎?

我想過的唯一方法就是聲明一個變量並將回調添加到變量中。這樣的事情:

var num; 
methods.userCount(function(count) { 
    num = count; 
}); 

res.render("../views/index", { 
    userCount: num 
}); 

但我不確定這是否是好的做法。有一個更好的方法嗎?

回答

1

你應該叫路由處理內部userCount功能不是周圍的其他方法:

app.get("/", function(req, res) { 
    methods.userCount(function(count) { 
    res.render("../views/index", { 
     userCount: count 
    }); 
    }); 
}); 

你如何計算計數是一個實現細節應該是userCount方法內。

我認爲更好的辦法是運行userCount方法作爲路由middleware和附加計數res.locals

app.use(function(req,res,next) { 
    // error handling omitted for simplicity 
    methods.userCount(function(count) { 
    res.locals.count = count; 
    next(); 
    }); 
}) 

app.get("/", function(req, res) { 
    res.render("../views/index", { 
    userCount: res.locals.count 
    }); 
}); 
+0

我得到了這個工作。但是,這與將所有回調值添加到對象並僅通過res.render傳遞對象有什麼不同? – dalton

+0

不確定你的意思和/或'userCount'是做什麼的。通過這種方法,您可以在每個請求中運行該功能。我想在啓動應用程序時運行它,這是一個不同的故事。如果是這樣的話,你可能想要將count添加到'app.locals'中,並且在調用'listen()'之前運行這個計數。 – Maroshii

+0

我需要在每個請求上運行它,這樣就可以很好地運行它。感謝您的幫助! – dalton

0

Step可能可以幫到你嗎?

function method(callback) { 
    var err = null; 
    var result = 123; 
    callback(err, result); 
} 
function method2(callback) { 
    var err = null; 
    var result2 = 'abc'; 
    callback(err, result2); 
} 

app.get("/", function(req, res) { 
    Step(
    function getData() { 
     method(this); // this is a callback for the next function on Step 
    }, 
    function getAnotherData(err, result) { // err, result is the reply of method() 
     req.result = result; // keep result to use on next function 
     method2(this); 
    }, 
    function render(err, result2) { 
     res.render('view', { 
     result: req.result, 
     result2: result2 
     }); 
    } 
) 
}); 
+0

我將如何整合,與將數據傳遞了同樣的看法多種功能? – dalton

+0

我不知道我是否瞭解你,但我已經更新了我的回覆,向你介紹「步驟」。它幫助你? – Arthur

+0

我不明白這一點。在我看來,以這種方式進行這種操作與將每個回調添加到變量中差不多。 – dalton