[英]How does response work inside callback in Express/Node?
我有一個異步 function 從文件中獲取一些數據,然后調用回調 function 以返回結果:
static fetchAll(callback){
fs.readFile(pathToDB, (err, fileContent) => {
if(err){
callback([]);
return;
}
callback(JSON.parse(fileContent));
});
}
然后我在我的一條路線 controller 函數中調用 function 函數,方法是傳入接收數據時觸發 res.render() 的回調:
const getShop = (req, res, next) => {
Product.fetchAll(products => {
console.log("Products received!, rendering");
res.render('shop', { prods: products, pageTitle: 'Shop', path: '/'});
});
console.log("leaving!");
};
我的問題是:
它不等待回調。 它將在console.log("Products received, rendering")
)之前執行 console.log console.log("leaving ")
) 。 只有在文件被讀取之后,它的數據才會被傳遞到res.render
部分。 但是到那時 Node 已經繼續前進了。
Promise 和回調在底層是一回事。 所以這是個人喜好問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.