承诺es6和超级代理

承诺es6和超级代理

本文介绍了承诺es6和超级代理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将es6 promise与superagent一起使用.我正在尝试调用一个函数,该函数具有包装在其中的超级代理请求.

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

我遇到错误

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

好像数据是在浏览器的dev工具中返回的,但是我无法在.then函数中找到它.我怎样才能从诺言中得到回应.

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.

推荐答案

end方法回调返回的内容无关紧要,因为当您获得响应和回调执行的结果时,它将异步执行无处使用.在此处和在源代码中. end方法返回this,因此在您的第二个示例中,您正在解决superagent无响应.要获得响应,您的post方法必须类似于:

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

这篇关于承诺es6和超级代理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 01:45