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;
結(jié)果:
問題解答
回答1:Promise.prototype.then()
無論什么時(shí)候返回的都是另外一個(gè)Promise對象,then()方法接受的參數(shù)是回調(diào)函數(shù),你只能控制回調(diào)函數(shù)的返回值,不能控制then()方法的返回值。手機(jī)打字不方便,有疑問的話,等我用電腦回答。
回答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;
這樣寫就行
相關(guān)文章:
1. mysql數(shù)據(jù)庫每次查詢是一條線程嗎?2. css - 關(guān)于ul的布局3. docker不顯示端口映射呢?4. 使用uuid,并不能利用mysql的索引,有什么解決辦法?5. javascript - 數(shù)組原聲方法中的一段代碼6. javascript - 前端開發(fā) 本地靜態(tài)文件頻繁修改,預(yù)覽時(shí)的緩存怎么解決?7. android - 優(yōu)酷的安卓及蘋果app還在使用flash技術(shù)嗎?8. JavaScript如何循序漸進(jìn),有效的學(xué)習(xí)?看不下去怎么辦?9. python - linux怎么在每天的凌晨2點(diǎn)執(zhí)行一次這個(gè)log.py文件10. java - public <T> T findOne(T record) 這是什么意思
