Promises es6 和 superagent

Promises es6 and superagent

我正在尝试将 es6 promises 与 superagent 结合使用。我正在尝试调用一个包含超级代理请求的函数。

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

这是包装超级代理的函数

  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

当我将函数的 return 更改为

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

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

end 方法回调返回什么并不重要,因为它是在您获得响应时异步执行的,并且回调执行的结果无处使用。查看源代码中的here and hereend 方法 returns 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);
            });
    });
}

有时您想避免由 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);
            });
    });
}

这是一个更简洁的版本,以防您需要它来处理很多请求

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

使用 ES6,您可以将 async/await 与 Promise and Generator support 一起使用:

const res = await request.get(url);

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