如何解决Javascript api get 调用返回响应,但在与 .then 链接时未定义
我有以下代码段。 api 调用成功,api 返回预期数据。
但是,当我在 .then(payload)
块内执行控制台日志并记录有效负载时,它是未定义的。这是为什么?
return API.get.MyData()
.then(response => {
console.log('response', response); // this is valid
response.json();
})
.then(payload => {
console.log('payload', payload); // this is undefined... why???
};
解决方法
您需要返回 response.json()
才能在链式 .then
通常,您会执行以下操作:
fetch(...).then(r => r.json()).then(console.log);
隐式返回 r.json()
,但由于您使用的是 () => { ... }
,因此您需要显式 return
。
return API.get.MyData()
.then(response => {
console.log('response',response); // this is valid
return response.json();
})
.then(payload => {
console.log('payload',payload); // this is undefined... why???
};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。