简体   繁体   English

如何在Node.js中将子函数的值返回父函数?

[英]How to return value from child function to parent function in Node.js?

I want a value from child function to the parent function in a Node.js and use that value in another file. 我想要一个从子函数到Node.js父函数的值,并在另一个文件中使用该值。 Being asynchronous flow the output of d.promise is pending. 作为异步流, d.promise的输出正在等待处理。
How can I get the value of d.promise as fulfilled with the data passed in the arangoFunction.js file in the queryCheck variable in the site.js file? 我怎样才能得到的值d.promise与中传递的数据符合arangoFunction.js文件中queryCheck可变site.js文件?

Database used : ArangoDB 使用的数据库:ArangoDB

site.js snippet site.js代码段

var arangoFunc = require('./arangoFunction'), queryCheck;
queryCheck = arangoFunc.saveData(data, roleCollection, res);
console.log(queryCheck);

arangoFunction.js snippet arangoFunction.js代码段

var q = require('q');
var d = q.defer();
    exports.saveData = function(data, collectionName, res){
          var collectionData = db.collection(collectionName);
          collectionData.save(data, function(e, o){
              if(e) {
                console.error(e);
                res.status(e.response.statusCode).send(e.response.statusMessage);
                d.reject(false);
              }
              else {
                res.send(data);
                d.resolve(data);
              }
            });
            return d.promise;
        }

Output of site.js snippet site.js代码段的输出

{ state: 'pending' }

arangoFunction.js arangoFunction.js

exports.saveData = function(data, collectionName, res){
  var collectionData = db.collection(collectionName);
  return q.Promise(function(resolve, reject, notify){
    collectionData.save(data, function(e, o){
      if(e) {
        console.error(e.response.statusMessage);
        res.status(e.response.statusCode).send(e.response.statusMessage);
        reject(e);
      }
      else {
        res.send(data);
        resolve(data);
      }
    });
  });
}

site.js site.js

arangoFunc.saveData(data, roleCollection, res).then(function(value){
 // do whatever with the returned data
}, function(err){
 // error handling
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM