Promises es6 and superagent

rross picture rross · Jan 15, 2015 · Viewed 12.4k times · Source

I'm attempting to use es6 promises with superagent. I'm attempting to call a function that has a superagent request wrapped inside.

Request.post(buildReq).then(res => {
 if (res.ok) {//process res}
});

Here is the function wrapping superagent

  static post(params) {
    superagent
      .post(params.url)
      .send(params.payload)
      .set('Accept', 'application/json')
      .end((error, res) => {
        return this.Promise.resolve(res);
      })
      .bind(this);
  }

I'm getting an error

enter code here Uncaught TypeError: Cannot read property 'then' of undefined

When I change the return of the function to

static post(params) {
    return Promise.resolve(superagent
      .post(params.url)
      .auth(params.auth.username, params.auth.password)
      .send(params.payload)
      .set('Accept', 'application/json')
      .end((error, res) => {
        return this.Promise.resolve(res);
      })
    );
  }

It looks like the data is returned in my browser's dev tools, but I cannot get to it within the .then function. How can I get the response from the promise.

Answer

alexpods picture alexpods · Jan 15, 2015

It doesn't matter what you're returning from the end method callback, as it asynchronously executed when you've get response and result of callback execution is nowhere used. Look here and here in the source code. end method returns this, so in your second example you're resolving superagent not response. To get response your post method must looks like:

static post(params) {
    return new Promise((resolve, reject) => {
        superagent
            .post(params.url)
            .auth(params.auth.username, params.auth.password)
            .send(params.payload)
            .set('Accept', 'application/json')
            .end((error, res) => {
                error ? reject(error) : resolve(res);
            });
    });
}