简体   繁体   中英

Curried JavaScript function for fluent API

I want to write a default callback for HTTP-requests made with superagent . The calls are all made with the async.parallel() framework and the overall result handled together. The callback should handle the results from the HTTP-requests and return a default value, if an error occured. The default value can be specified, but null will be used if it was not set.

I want to construct my handler using a fluent syntax like this:

handle(done).withDefaultValue([]) (empty array is set as default value)

handle(done) (null is used as default value)

I'm relatively new to function currying. Here's what I've tried: I created a Node module which should be eventually used like this:

My code in 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
}

My code in 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){
})

Above code works for the first call (the one with withDefaultValue([]) , but not for the second call:

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

What am I doing wrong?

This seems to do the trick:

 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)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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