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

Node async waterfall route with functions split in multiple files

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

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")
  }
}

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

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

您的瀑布函数需要更改如下: 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")
  }
}