React Native 中的"双重获取"调用问题



在React Native函数中使用"嵌套"Fetch调用时遇到问题。第一个Fetch似乎工作正常,但第二个Fetch出现了错误。这是代码:

//****CALL TWO FETCH REQUESTS...
const data = { passkey: '12345', callup: 'name' };
const secondary = { passkey: '12345', callup: 'name' };
fetch('https://myremoteserveraddress', {
method: 'POST', 
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then(function(response) {
if (response.ok) {
return response.json();
} else {
return Promise.reject(response);
}
})
.then(data => {
// Store the post data to a variable
_post = data;
console.log('Success on FIRST FETCH:', data);
console.log('answer is:', data.answer);
console.log('answer is:', _post.answer);
// Fetch another API
fetch('https://myremoteserveraddress', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(secondary),
})
})
.then(function (response) {
if (response.ok) {
return response.json();
} else {
return Promise.reject(response);
}
})
.then(function (userData) {
console.log('Returned from BOTH fetch calls');  //does not write to console
console.log(_post, userData);  //does not write to console
this.vb.start();
})
.catch((error) => {
console.error('Error in onPressPublishBtn:', error);
});
//****

第二个Fetch调用似乎返回了"undefined",尽管它与第一个Fetch呼叫相同,但似乎工作成功。返回的错误是";TypeError:undefined不是对象(正在评估"response.ok"("。如果有人能就问题提出建议,我将不胜感激。提前谢谢。

您应该从第二个then(…(块返回一个Promise,以便将响应传递给第三个then(..(

// Fetch another API
return fetch('https://myremoteserveraddress', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(secondary),
})

最新更新