Reputation: 585
Not getting api response of 3500 records inside the promise method. If I call api using setTimeout(), it is working and getting all the data.
Please find the sample code below, (calling apiCall in async method only)
let data = await apiCall();
function apiCall(){
return new Promise((resolve,reject)=>{
let options = {method:'get'}
fetch('http://example.com/getData',options).then(data => {
resolve(data);
});
});
}
Upvotes: 3
Views: 1242
Reputation: 6718
This line here, let data = await apiCall();
, is invalid if you're not calling inside async
function becuase await
is valid only inside async
function.
The proper syntax for using async/await
is:
async function myFunc() {
let result = await getSomething()
...
}
Also fetch
API supports Promise
, so in your code you could do:
// note async keyword
async function apiCall(){
let options = {method:'get'}
try {
let response = await fetch('http://example.com/getData',options) // response is also a promise so
let data = await response.json(); // data contains the result
console.log(data);
} catch (err) {
console.error(err)
}
}
Say if you do return data
in your apiCall
function then the result is also wrapped in promise
by async
function. So you'll have to:
apiCall().then(result => console.log(result))
. And again async/await
usage is above ^
Upvotes: 1
Reputation: 2434
let data = await apiCall();
function apiCall(){
let options = {method:'get'};
return fetch('http://example.com/getData', options);
}
try like this and it should work fine.
Upvotes: 1