0

In the package Super Agent, the docs state:

A request can be initiated by invoking the appropriate method on the request object, then calling .then() (or .end() or await) to send the request.

request
   .get('/search')
   .then(res => {
      // res.body, res.headers, res.status
   });

However SuperAgent supports method chaining such as

request.get('/search')
  .set('header1','value')
  .set('header2','value')

to modify the request before it is sent. So...

How does the request object know when the method chain is finished so it doesn't prematurely send?

My theory is that any chain off of the request object returns a thenable object which is able to be await'd or .then()'d, and when it is, it will fire off a request and return an actual promise.

I looked around in the superagent repo and couldn't find anything like that. How else might waiting to send the request until the method chain is complete be accomplished?

Community
  • 1
  • 1
Jordan
  • 3,813
  • 4
  • 24
  • 33
  • 1
    Yes. As you quoted the docs, "*calling `.then()` or `.end()`*" does send the request. – Bergi Nov 15 '19 at 20:51
  • 1
    Also [that's what the code does](https://github.com/visionmedia/superagent/blob/5b86fd397264cb7b84634fa7ff00ad82214aa473/src/request-base.js#L238-L264) – Bergi Nov 15 '19 at 20:54

1 Answers1

1

You can never go wrong by just going to the source and looking. So, if you look at the code for .then(), you will see that it calls .end() on itself.

So, the request is sent when .then() or .end() is called. Up until then, other methods are just configuring the request object.

And, using await will invoke .then() on the promise.

Also, if you search for .end in that above source file reference, you will see dozens of code examples that all show .end() at the end of the chain. That is the original design architecture for superagent. Then, when promises came along, support for .then() was added and it uses .end() internally.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • So does that mean that `await` sends it too because the object is `thenable`? – Jordan Nov 15 '19 at 20:56
  • 2
    @Jordan - Yes. `await` actually invokes `.then()` since that's the only way you know when a promise is done. – jfriend00 Nov 15 '19 at 20:56
  • 1
    @Jordan `await` is no magic, it just [calls `.then` if the awaited object is thenable](https://stackoverflow.com/q/49086056/1048572). – Bergi Nov 15 '19 at 20:57