node.js - express won't refresh data
漂亮男人
漂亮男人 2017-05-31 10:38:55
0
2
723

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.

漂亮男人
漂亮男人

reply all(2)
阿神

After calling the Promise method, you need to return the Promise object

phpcn_u1582

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:

var testData='testData'
var execute=0;
var testPromise = new Promise((resolve, reject) => {
    execute++;
    setTimeout(function () {
        resolve(testData);
    }, 1000);
})

testPromise.then((data) => {
    console.log(1,data);
    testData='newData'
})

setTimeout(function () {
    testPromise.then((data) => {
        console.log(2,data);
        console.log('执行次数:'+execute)
    })
}, 2000);


//最终输出
// 1 'testData'
// 2 'testData'
// 执行次数:1
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!