gpt4 book ai didi

ecmascript-6 - promise es6 和 superagent

转载 作者:行者123 更新时间:2023-12-04 02:34:33 25 4
gpt4 key购买 nike

我正在尝试将 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 返回什么并不重要方法回调,因为它在您获得响应时异步执行,并且没有使用回调执行的结果。看 herehere在源代码中。 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com