search

Home  >  Q&A  >  body text

Does node.js return promise objects instead of data through module.exprots?

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:

習慣沉默習慣沉默2843 days ago497

reply all(2)I'll reply

  • 我想大声告诉你

    我想大声告诉你2017-05-16 13:25:03

    Promise.prototype.then()

    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.

    reply
    0
  • 过去多啦不再A梦

    过去多啦不再A梦2017-05-16 13:25:03

    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;

    Just write it like this

    reply
    0
  • Cancelreply