使用一个函数中的值转换成另一个NodeJS表达的函数

时间:2019-01-14 17:05:46

标签: javascript node.js express

我想返回在第一个Function CreateTag中声明的值,并将其用作第二个Function CreateStream中的变量,但是它将不起作用。

我正在使用nodejs Express。 我尝试使用 RETURN ,但是它不起作用。 我已经以不同的方式尝试过,但仍然无法正常工作。

请问有人可以帮我吗?

'use strict';
var express = require('express');
var router = express.Router();

/* GET home page. */

//Function 1: createTag
      var createTag = function hi (TanentValue) {
          var https = require('https');
          var data = JSON.stringify({
        name: TanentValue,
        schemaPath: "Tag"
    });
    var options = {
        hostname: 'qlik_dev.be',
        path: '/meteor/qrs/tag?xrfkey=1234567890123456',
        method: 'POST',
        headers: {
            'x-qlik-xrfkey': '1234567890123456',
            'hdr-usr': 'gak\\gaka',
            'Content-Type': 'application/json'
        },
    };

        var req = https.request(options, (res) => {
        //console.log(res)

        res.on('data', (d) => {
            console.log("hi tag")
            var getResult = "GaLvAnI"; // ----> return this and use it into the function createStream
            return getResult;
        })
    })
        ;
    req.on('error', (error) => {
        console.error(error)

    });

    req.write(data);
    req.end();
}
//Function 2: createStream
var createStream = function (TanentValue) {
    var https = require('https');
    var galvani = hi(); // --------> here I made a variable to call return value
    var data = JSON.stringify({
        name: TanentValue,
    });

    var options = {
        hostname: 'qlik_dev.be',
        path: '/meteor/qrs/stream?xrfkey=1234567890123456',
        method: 'POST',
        headers: {
            'x-qlik-xrfkey': '1234567890123456',
            'hdr-usr': 'gak\\gaka',
            'Content-Type': 'application/json'
        },
    };

    var req = https.request(options, (res) => {

        res.on('data', (d) => {
            console.log(galvani); // -----> use the variable here
        })
    })
        ;
    req.on('error', (error) => {
        console.error(error)
    });

    req.write(data);
    req.end();
}
//homepage
router.get('/', function (req, res) {
    res.render('index', { title: 'MCS Test' });
});
//create
router.post('/create', function (req, res) {
    //create tag
    console.log('POST / Call Create Tag');
    createTag(req.body.TanentValue);
    //create stream
    console.log('POST / Call Create Stream');
    createStream(req.body.TanentValue);

    res.send('Stream and Tag has been created');
});
module.exports = router;

3 个答案:

答案 0 :(得分:0)

您不能直接从异步函数返回值。你必须使用诺言。像这样的东西:

'use strict';
var express = require('express');
var router = express.Router();

/* GET home page. */

//Function 1: createTag
var createTag = function (TanentValue) { // function should be anonymouse
  return new Promise((resolve, reject) => {
    var https = require('https');
    var data = JSON.stringify({
      name: TanentValue,
      schemaPath: "Tag"
    });
    var options = {
        hostname: 'qlik_dev.be',
        path: '/meteor/qrs/tag?xrfkey=1234567890123456',
        method: 'POST',
        headers: {
            'x-qlik-xrfkey': '1234567890123456',
            'hdr-usr': 'gak\\gaka',
            'Content-Type': 'application/json'
        },
    };

        var req = https.request(options, (res) => {
        //console.log(res)

        res.on('data', (d) => {
            console.log("hi tag")
            var getResult = "GaLvAnI"; // ----> return this and use it into the function createStream
            resolve(getResult); // success call
        })
    })
        ;
    req.on('error', (error) => {
        reject(error); // error call

    });

    req.write(data);
    req.end();
  });
    
}
//Function 2: createStream
var createStream = function (TanentValue) {
    createTag().then((val) => {
      var https = require('https');
      var galvani = val; // use that value from sucess call
      var data = JSON.stringify({
          name: TanentValue,
      });

      var options = {
          hostname: 'qlik_dev.be',
          path: '/meteor/qrs/stream?xrfkey=1234567890123456',
          method: 'POST',
          headers: {
              'x-qlik-xrfkey': '1234567890123456',
              'hdr-usr': 'gak\\gaka',
              'Content-Type': 'application/json'
          },
      };

      var req = https.request(options, (res) => {

          res.on('data', (d) => {
              console.log(galvani); // -----> use the variable here
          })
      })
          ;
      req.on('error', (error) => {
          console.error(error)
      });

      req.write(data);
      req.end();
    })
    .catch((error) => {
      // handle error from createTag function here
    });
    
}
//homepage
router.get('/', function (req, res) {
    res.render('index', { title: 'MCS Test' });
});
//create
router.post('/create', function (req, res) {
    //create tag
    console.log('POST / Call Create Tag');
    createTag(req.body.TanentValue);
    //create stream
    console.log('POST / Call Create Stream');
    createStream(req.body.TanentValue);

    res.send('Stream and Tag has been created');
});
module.exports = router;

答案 1 :(得分:0)

您可以仅使用回调函数或promise来解决它。

  1. 使用回调。

'use strict';
var express = require('express');
var router = express.Router();

/* GET home page. */

//Function 1: createTag
var createTag = (TanentValue, callback) => {
    var https = require('https');
    var data = JSON.stringify({
        name: TanentValue,
        schemaPath: "Tag"
    });

    var options = {
        hostname: 'qlik_dev.be',
        path: '/meteor/qrs/tag?xrfkey=1234567890123456',
        method: 'POST',
        headers: {
            'x-qlik-xrfkey': '1234567890123456',
            'hdr-usr': 'gak\\gaka',
            'Content-Type': 'application/json'
        },
    };

    var req = https.request(options, (res) => {

        res.on('data', (d) => {
            console.log("hi tag")
            var getResult = "GaLvAnI"; // ----> return this and use it into the function createStream

            callback(false, getResult);
        })
    });

    req.on('error', (error) => {
        //console.error(error)
        callback(true, error);
    });

    req.write(data);
    req.end();
}



//Function 2: createStream
var createStream = (TanentValue, callback) => {
    var https = require('https');
    var data = JSON.stringify({
        name: TanentValue,
    });

    var options = {
        hostname: 'qlik_dev.be',
        path: '/meteor/qrs/stream?xrfkey=1234567890123456',
        method: 'POST',
        headers: {
            'x-qlik-xrfkey': '1234567890123456',
            'hdr-usr': 'gak\\gaka',
            'Content-Type': 'application/json'
        },
    };

    createTag(TanentValue, (is_error, galvani) => {
        if(err || !data){
            // do error handling...
            callback(true); // true for there was an error
        }else{
            var req = https.request(options, (res) => {

                res.on('data', (d) => {
                    callback(false);
                    console.log(galvani); // -----> use the variable here
                })
            });

            req.on('error', (error) => {
                callback(true);
                console.error(error)
            });

            req.write(data);
            req.end();
        }
    })
}


//homepage
router.get('/', function (req, res) {
    res.render('index', { title: 'MCS Test' });
});

//create
router.post('/create', function (req, res) {
    /*
    // Since the stream seems to depend on the tag created,
    // you don't need to call createTag explicitly because
    // it is always/already called from createStream.

    //create tag
    console.log('POST / Call Create Tag');
    createTag(req.body.TanentValue, function(is_error, data){
        if(!is_error){
            // do something
        }else{
            // do error handling
            console.error(error);
            res.send('Tag could not be created, please try later again..');
        }
    });
    */

    //create stream
    console.log('POST / Call Create Stream');
    createStream(req.body.TanentValue, is_error => {
        if(!is_error){
            res.send('Stream and Tag has been created');
        }else{
            res.send('Stream could not be created, please try later again..');
        }
    });

});
module.exports = router;

  1. 使用承诺

'use strict';
var express = require('express');
var router = express.Router();

/* GET home page. */

//Function 1: createTag
var createTag = TanentValue => {
    var https = require('https');
    var data = JSON.stringify({
        name: TanentValue,
        schemaPath: "Tag"
    });

    var options = {
        hostname: 'qlik_dev.be',
        path: '/meteor/qrs/tag?xrfkey=1234567890123456',
        method: 'POST',
        headers: {
            'x-qlik-xrfkey': '1234567890123456',
            'hdr-usr': 'gak\\gaka',
            'Content-Type': 'application/json'
        },
    };

    return new Promise((resolve, reject) => {
        var req = https.request(options, (res) => {

            res.on('data', (d) => {
                console.log("hi tag")
                var getResult = "GaLvAnI"; // ----> return this and use it into the function createStream

                resolve(getResult);
            })
        });

        req.on('error', (error) => {
            //console.error(error)
            reject(error);
        });

        req.write(data);
        req.end();
    })
}



//Function 2: createStream
var createStream = TanentValue => {
    var https = require('https');
    var data = JSON.stringify({
        name: TanentValue,
    });

    var options = {
        hostname: 'qlik_dev.be',
        path: '/meteor/qrs/stream?xrfkey=1234567890123456',
        method: 'POST',
        headers: {
            'x-qlik-xrfkey': '1234567890123456',
            'hdr-usr': 'gak\\gaka',
            'Content-Type': 'application/json'
        },
    };

    createTag(TanentValue).then( galvani => {
        return new Promise((resolve, reject) => {
            var req = https.request(options, (res) => {

                res.on('data', (d) => {
                    console.log(galvani); // -----> use the variable here
                    resolve(d);
                })
            });

            req.on('error', (error) => {
                console.error(error)
                reject({ msg: 'request error while creating the stream', error: error})
            });

            req.write(data);
            req.end();
        })
    }).catch( error => {
        // do error handling...
        reject({msg: 'Error while creating a tag', error: error}); // true for there was an error
    });
}


//homepage
router.get('/', function (req, res) {
    res.render('index', { title: 'MCS Test' });
});

//create
router.post('/create', function (req, res) {
    /*
    // Since the stream seems to depend on the tag created,
    // you don't need to call createTag explicitly because
    // it is always/already called from createStream.

    //create tag
    console.log('POST / Call Create Tag');
    createTag(req.body.TanentValue).then( data => {
        // do something
    }).catch( error => {
        // do error handling
    });
    */

    //create stream
    console.log('POST / Call Create Stream');
    createStream(req.body.TanentValue).then( data => {

        res.send('Stream and Tag has been created');

    }).catch(error => {
        // 'Stream could not be created, please try later again..'
        res.send(error.msg);
    });

});
module.exports = router;

答案 2 :(得分:0)

很满!谢谢你的作品! 但是,当使用Promise将数据(Json)从函数1传递到函数2时,该数据(json)在函数2中是未定义的。 >

当它是json时为什么会给我'undefine'吗?

     //var id;
    var req = https.request(options, (res) => {
        //console.log(res)
        res.setEncoding('utf8');
        res.on('data', function (data) {
            var json = JSON.parse(data);
            var TagId = JSON.stringify(json[0]);
            console.log("2 hi getTap");
            console.log(TagId); // -------> here it works well
            resolve(TagId);
        });
    });

        var req = https.request(options, (res) => {

            res.on('data', (d) => {
                console.log("3 hi createStream");
                console.log(galvani); // -------> here it doesn't work.. it gives me undefine

            })
        });

here a printscreen of response