After I update the data in the database, refreshing the page will not display the new data.
The code is as follows
data.js
var http=require('http');
var p = new Promise(function(resolve, reject){
//做一些异步操作
var json = '';
http.get('http://localhost/getinfo', function (res) {
res.on('data', function (data) {
json += data;
}).on('end',function (){
json = JSON.parse(json);
resolve(json);
})
}).on('error', function (e) {
console.error(e);
});
});
module.exports=p;
index.js
var express = require('express');
var router = express.Router();
var data=require('../serve/data.js');
router.get('/', function(req, res, next) {
data.then(function(data){
var title=new Array;
var img=new Array;
var pbi=new Array;
for(i=0;i<data.length;i++){
title[i]=data[i].pname;
console.log(title[i]);
img[i]=data[i].psrc;
pbi[i]=data[i].pbi;
}
if(req.session.un==null)req.session.un="未登录";
res.render('index',{
title:title,
un:req.session.un,
img:img,
pbi:pbi
});
});
if(req.session.un){
console.log(req.session.un);
}
});
/* GET login page. */
module.exports = router;
The solution is to write the content in data.js to index.js (write it under the routing control function), so now I have a question, what is the mechanism of require? Execute? But it still doesn't work if I put the require under the router.get function, so I would like to ask how to refresh the data if I want to write it separately.
After calling the Promise method, you need to return the Promise object
Promise state is irreversible and non-repeatable.
When data.js is loaded, p is assigned to a Promise object and subsequently executed, then becomes the Resolved state, and then handed over to index.js. When
http.get
ends, the status of p has been locked to Resolved (assuming success). No matter how you refresh the page later, p will still be the original p, and a new Promise will not be regenerated.You can see this example: