Does node.js return promise objects instead of data through module.exprots?
習慣沉默
習慣沉默 2017-05-16 13:23:03
0
2
489

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:

習慣沉默
習慣沉默

reply all(2)
我想大声告诉你
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.

过去多啦不再A梦
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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template