节点异步瀑布路由,功能分为多个文件

时间:2016-07-09 16:38:16

标签: node.js express node-async

我在单独的文件中有两个函数,我想使用异步瀑布在一个路径中一起调用。设置require,调用函数和传递参数时遇到问题。我哪里错了?

route.js

router.get('/bothFunctions', require('./bothFunctions')

bothFunctions.js

var async = require("async")
module.exports = function(req, res, next) {
  var userName = req.user.username
  var oneFunction = require('./oneFunction')
  var twoFunction = require('./twoFunction')
  var asyncFinally = function(err, results) {
    if(err) return res.send(err)
    return res.send(results)
  }
  async.waterfall([oneFunction(userName), twoFunction], asyncFinally)
}

oneFunction.js

var request = require("request")
module.exports = function(userName, callback) {
  request('/address', function(err, res, body) {
    if(err) return (err, null)
    // do stuff with userName
    return(null, arg2)
  }
}

twoFunction.js

var request = require("request")
module.exports = function(err1, arg2, callback) {
  if(err1) return("error", null)
  request('/address', function(err2, res, body) {
    if(err2) return (err2, null)
    // do stuff with arg2
    return(null, "success")
  }
}

2 个答案:

答案 0 :(得分:0)

我遇到的问题是async.waterfall。为了将参数传递给瀑布中的第一个函数,您必须使用以下代码绑定它们:

async.waterfall([async.apply(oneFunction, "Name"), twoFunction], asyncFinally)

答案 1 :(得分:0)

您的瀑布功能需要改变如下: oneFunction.js

var request = require("request")
module.exports = function(username){
return function(callback) {
  request('/address', function(err, res, body) {
    if(err) return (err, null)
    // do stuff with userName
    return(null, arg2)
  }
}
}

twoFunction.js

var request = require("request")
module.exports = function(arg2, callback) {
  request('/address', function(err2, res, body) {
    if(err2) return (err2, null)
    // do stuff with arg2
    return(null, "success")
  }
}