承诺es6和superagent

时间:2015-01-15 15:32:44

标签: ecmascript-6 superagent es6-promise

我试图使用es6承诺与superagent。我试图调用一个包含在其中的superagent请求的函数。

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

这是函数包装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);
  }

我收到错误

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

当我将函数的返回值更改为

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

看起来数据是在我的浏览器开发工具中返回的,但我无法在.then函数中找到它。我怎样才能得到承诺的回应。

5 个答案:

答案 0 :(得分:29)

end方法回调中返回的内容并不重要,因为当您获得响应并且回调执行的结果未被使用时,它会异步执行。在源代码中查看herehereend方法返回this,因此在您的第二个示例中,您正在解析superagent无响应。要获得回复,您的post方法必须如下:

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

答案 1 :(得分:6)

有时您希望避免new Promise(...)导致的缩进级别,然后您可以直接使用Promise.rejectPromise.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);
            });
    });
}

答案 2 :(得分:1)

这是一个更简洁的版本,如果您需要大量请求

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

答案 3 :(得分:0)

使用ES6,您可以对Promise and Generator support使用async / await:

const res = await request.get(url);

答案 4 :(得分:0)

v2.0.0开始,superagent提供了与ES6兼容的.then()。这样您的代码就可以成为

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;
        });
}
相关问题