Search code examples
javascriptnode.jssuperagent

Can someone explain how chained functions work when there is a prototype function in the chain in JS?


I'm trying to separate the chained calls from:

request
  .post('/upload')
  .attach('image1', 'path/to/felix.jpeg')
  .attach('image2', imageBuffer, 'luna.jpeg')
  .field('caption', 'My cats')
  .end(callback);

to:

request
  .post('/upload')

request
  .attach('image1', 'path/to/felix.jpeg')
  .attach('image2', imageBuffer, 'luna.jpeg')
  .field('caption', 'My cats')
  .end(callback);

I'm probably thinking about this wrong and missing a concept, but I would like to know why that doesn't work and how does .attach (being a function added to the prototype of request) does get called in the first instance. And any pointers to any resources

Ref: https://github.coventry.ac.uk/askaria/304CEM-LizoFile/blob/master/node_modules/superagent/docs/index.md#attaching-files

https://github.com/visionmedia/superagent


Solution

  • The request.post() call is actually returning something and then the next method .attach() is called on that returned data.

    You can use

    const req = request
      .post('/upload');
    
    req
      .attach('image1', 'path/to/felix.jpeg')
      .attach('image2', imageBuffer, 'luna.jpeg')
      .field('caption', 'My cats')
      .end(callback);