【问题标题】:Promises es6 and superagent承诺 es6 和超级代理
【发布时间】:2015-03-14 01:21:48
【问题描述】:

我正在尝试将 es6 Promise 与 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 函数中访问它。我怎样才能从承诺中得到回应。

【问题讨论】:

    标签: ecmascript-6 superagent es6-promise


    【解决方案1】:

    无论您从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);
                });
        });
    }
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

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

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

        【讨论】:

          【解决方案4】:

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

          【讨论】:

            【解决方案5】:

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

            const res = await request.get(url);
            

            【讨论】:

              猜你喜欢
              • 2019-02-08
              • 2018-04-10
              • 2016-07-18
              • 2016-06-29
              • 1970-01-01
              • 2016-04-02
              • 1970-01-01
              • 2016-11-20
              • 2018-11-28
              相关资源
              最近更新 更多