我查看了this question/answer,但无法使其满足我的需要。
我在async
文件中有一个offer.js
函数,需要从Controller文件中调用它。 offer.js
文件可正常工作并返回JSON数据。这是调用Controller文件,在继续页面的其余部分之前,我无法“等待”数据返回。
这是Controller文件的作用:
var router = require('express').Router(); // Express.js router functionality
const Offer = require('../models/offer'); // the offer.js file which has getAllOffers() async function
// call/return the data from getAllOffers() async function
var rsOffersAll = async function() {
return await Offer.getAllOffers();
}
// I would like rsOffersAll to have data before doing anything further at this point.
// if the homepage, supply the rsOffersAll data to the view.
router.get('/', function(req, res, next) {
res.render('index', { data: rsOffersAll }); // the data needs to be here. this should not run until the data is available to pass to the view
});
如何确保
var rsOffersAll
在执行router.get...
东西之前有数据? 最佳答案
在这里,rsOffersAll
是多余的,您可以在内部使用await
结果,但不要在路由处理程序中使用await
rsOffersAll
的结果。
router.get('/', async (req, res, next) => {
const data = await Offers.getAllOffers();
res.render('index', { data });
});