node.js通过module.exprots返回的是promise对象而非data?
问题描述
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;
结果:

问题解答
回答1:Promise.prototype.then()
无论什么时候返回的都是另外一个Promise对象,then()方法接受的参数是回调函数,你只能控制回调函数的返回值,不能控制then()方法的返回值。手机打字不方便,有疑问的话,等我用电脑回答。
回答2:var express = require(’express’);var router = express.Router();var data=require(’../serve/data.js’);/* GET home page. */router.get(’/’, function(req, res, next) { //var a=JSON.parse(getdata); data.then(function(data){console.log(data.total);res.render(’index’,{title:data.total}); }); });module.exports = router;
这样写就行
相关文章:
1. docker不显示端口映射呢?2. docker网络端口映射,没有方便点的操作方法么?3. 关于docker下的nginx压力测试4. javascript - Vue 自定义控件v-model双向绑定5. css3 - 新版支付宝 账单页面滑动时月份栏被下一个月给顶上去是什么效果6. javascript - 关于js原生事件的绑定与解除绑定7. 把h5放入webview里面,h5页面上下可以回弹,怎么可以去掉该效果8. css3 - 没明白盒子的height随width的变化这段css是怎样实现的?9. javascript - yo创建angular报错10. javascript - nodejs报错 打开localhost:3000 就报错

网公网安备