问题描述
我有以下代码段。 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???
};