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;
結果:
無論何時返回的都是另外一個Promise對象,then()方法接受的參數是回呼函數,你只能控制回呼函數的回傳值,不能控制then()方法的回傳值。手機打字不方便,有疑問的話,等我用電腦回答。
這樣寫就行