我正在尝试将 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 函数中访问它。我怎样才能得到承诺的回应。
你从返回什么并不重要end
方法回调,因为当您收到响应时它会异步执行,并且回调执行的结果不会被使用。看here https://github.com/visionmedia/superagent/blob/master/lib/client.js#L879 and here https://github.com/visionmedia/superagent/blob/master/lib/client.js#L815在源代码中。end
方法返回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);
});
});
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)