[英]React-Native : How to get callback of api call in another class
我正在打電話給網絡服務
這是我的代碼:
var result;
export function callPostApi(urlStr, params)
{
fetch(urlStr, {method: "POST", headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(params)})
.then((response) => response.json())
.then((responseData) => {
result = JSON.stringify(responseData)
})
.catch((error) => { console.error(error);
Alert.alert('Alert Title failure' + JSON.stringify(error))
})
.done();
return result
}
我從這里打電話:
callapi(){
var dict = {
email: 'at@gmail.com',
password: '123456',
}
result = callPostApi('http://demo.com', dict)
}
當前,我們希望以異步模式進行調用,但是代碼被編寫在此方法下,並在調用上述方法后立即執行
我希望在收到來自服務器的結果時進行回調,以便我可以執行以下方法編寫的代碼,這些代碼是在收到服務器的響應后執行的。
您需要使用Promises。
更改您的callPostApi
函數以返回Promise,然后可以鏈接其他then
, catch
和finally
調用。
export function callPostApi(urlStr, params) {
return fetch(urlStr, {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(params)
})
.then((response) => response.json())
.then((responseData) => {
result = JSON.stringify(responseData)
})
.catch((error) => {
console.error(error);
Alert.alert('Alert Title failure' + JSON.stringify(error))
});
}
callapi() {
callPostApi('http://demo.com', {
email: 'at@gmail.com',
password: '123456',
})
.then((response) => {
// Continue your code here...
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.