data.js
var http=require('http');
function runAsync(){
var p = new Promise(function(resolve, reject){
//做一些异步操作
var json = '';
http.get('http://localhost:8080/getJson?', 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);
});
});
return p;
}
**module.exports=runAsync().then(function(data){
console.log(data);
return data;
});**//注意这句,我明明返回的是runasync.then(。。。。)为什么他给我返回了runasync()
index.js
var express = require('express');
var router = express.Router();
var getdata=require('../serve/data.js');
/* GET home page. */
router.get('/', function(req, res, next) {
//var a=JSON.parse(getdata);
console.log(getdata);
res.render('index',{title:getdata.total});
});
module.exports = router;
result:
Whatever is returned is another Promise object. The parameter accepted by the then() method is the callback function. You can only control the return value of the callback function, not the return value of the then() method. It is inconvenient to type on a mobile phone. If you have any questions, please wait for me to answer on the computer.
Just write it like this