我正在尝试将 es6 promise 与 superagent 一起使用。我正在尝试调用一个包含 super 代理请求的函数。
Request.post(buildReq).then(res => {
if (res.ok) {//process res}
});
这是包装 super 代理的函数
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 函数中访问它。我怎样才能得到 promise 的回应。
最佳答案
您从 end
返回什么并不重要方法回调,因为它在您获得响应时异步执行,并且没有使用回调执行的结果。看 here和 here在源代码中。 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);
});
});
}
关于ecmascript-6 - promise es6 和 superagent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27967000/