熟练的API JavaScript函数

Curried JavaScript function for fluent API

本文关键字:JavaScript 函数 API      更新时间:2023-09-26

我想为使用超级代理发出的HTTP请求编写一个默认回调。所有的调用都是使用async.parallel()框架进行的,整体结果一起处理。回调应该处理HTTP请求的结果,并在发生错误时返回默认值。可以指定默认值,但如果未设置,则将使用null

我想使用一个流畅的语法来构建我的处理程序,比如:

handle(done).withDefaultValue([])(空数组设置为默认值)

handle(done)(默认值为空)

我对函数咖喱还比较陌生。以下是我尝试过的:我创建了一个节点模块,它最终应该像这样使用:

我在handle.js 中的代码

module.exports = function(done){
  this.withDefaultValue = function(defaultValue){
    return function(err, result){
      if(err){
        debug('handling error ' + err + ' and returning default value ' + defaultValue)
        return done(null, defaultValue)
      }
      // sanity check for null and empty objects
      result = _.isEmpty(result)?[]:result
      done(null, result)
    }
  }
  return this
}

我在somefile.js 中的代码

var handle = require('handle')
async.parallel([
   function(done){
     api.myApiCall(arg1, arg2, handle(done).withDefaultValue([]))
   },
   function(done){
     api.myOtherApiCall(arg1, arg2, handle(done))
   }
], function(err, result){
})

以上代码适用于第一个调用(具有withDefaultValue([])的调用,但不适用于第二个调用:

Unhandled Error: handle(...).withDefaultValue is not a function

我做错了什么?

这似乎奏效了:

console.log = x => document.write(x + "<br>");
function handle(func) {
    var handler = function(param) {
        console.log('doing stuff...');
        func(param);
    };
    var ret = handler.bind(this, "default");
    ret.withDefault = function(val) {
        return handler.bind(this, val);
    }
    return ret;
}
function done(param) {
    console.log(param)
}
setTimeout(handle(done));
setTimeout(handle(done).withDefault(123));