Promises es6 and superagent
Asked Answered
D

5

11

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.

Determinable answered 15/1, 2015 at 15:32 Comment(0)
H
29

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);
            });
    });
}
Howerton answered 15/1, 2015 at 18:30 Comment(0)
T
6

Sometimes you'd like to avoid an indentation level caused by new Promise(...) then you can use directly Promise.reject and Promise.resolve.

static post(params) {
    return superagent
            .post(params.url)
            .auth(params.auth.username, params.auth.password)
            .send(params.payload)
            .set('Accept', 'application/json')
            .end((error, res) => {
                return error ? Promise.reject(error) : Promise.resolve(res);
            });
    });
}
Thornton answered 13/2, 2016 at 9:56 Comment(0)
P
2

As of v2.0.0, superagent provides an ES6-compatible .then(). So your code could become

static post(params) {
return superagent
        .post(params.url)
        .auth(params.auth.username, params.auth.password)
        .send(params.payload)
        .set('Accept', 'application/json')
        .then((res) => {
            return res;
        });
}
Piassava answered 15/10, 2019 at 8:47 Comment(0)
C
1

This is a more consise version, in case you need it for a lot of requests

import request from "superagent";

const withPromiseCallback = (resolve, reject) => (error, response) => {
  if (error) {
    reject({error});
  } else {
    resolve(response.body);
  }
};

export const fetchSuggestions = (search) => new Promise((resolve, reject) =>
 request.
    get("/api/auth/get-companies/0/50").
    type("form").
    set("Accept", "application/json").
    query({
      search,
    }).
    end(withPromiseCallback(resolve, reject))
);

export const fetchInitialInformation = () => new Promise((resolve, reject) =>
  request.
    get("/api/auth/check").
    set("Accept", "application/json").
    end(withPromiseCallback(resolve, reject))
);
Calibrate answered 27/7, 2016 at 12:30 Comment(0)
G
-1

With ES6, you can use async/await with Promise and Generator support:

const res = await request.get(url);
Geraldgeralda answered 7/1, 2019 at 15:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.