fetch API not returning response - javascript

async function getQuote() {
console.log("heya");
const url = "/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1";
const response = await fetch(url);
console.log(response);
return await response.json();
// console.log("hello", quote);
}
getQuote().then(result => {
console.log("here");
console.log(result.shift());
});
This is my code. Why isnt response returning something?
Link: https://codepen.io/anon/pen/JJYGNJ?editors=1012

Related

Fetch API: get promisestate of response

I want to fetch promiseState of my response.
How do I do that?
This is my code:
let my_url = 'google.com';
const txtPromise = fetch('https://api.codetabs.com/v1/proxy?quest=' + my_url).then(resp => resp.text());
console.log(txtPromise); //showing Promise {<pending>}
You can use async await for that:
async function getData() {
const response = await fetch(
'https://jsonplaceholder.typicode.com/todos/1'
);
if (response.ok) {
const data = await response.text();
console.log(data);
}
}
getData();

React native async function returns empty object

I am trying to get a token stored in securestore, and pass it to url. When I try to call the api the value of the token is just an empty object. I am able to see the value t here if I alert in readToken function. Its not passed to getMovies function.
const readToken = async () => {
try {
const storedToken = await SecureStore.getItemAsync('token');
return storedToken;
} catch (e) {
console.log(e);
}
};
const getMovies = async () => {
try {
let url = 'https://someurl.de/api/getschichten/?userid=9&token='+readToken();
alert(url);
const response = await fetch(url);
const json = await response.json();
setData(json);
} catch (error) {
console.error(error);
} finally {
setLoading(false);
}
}
So, I changed my code according to kipnodels. Here's my code that works
let myToken = await readToken();
let url = 'https://esm.nvii-dev.de/api/getschichten/?userid=9&token='+myToken;

What is the best way to handle paginated API in Javascript?

I am trying to consume an API which returns structure below.
{
data: [{...},{...},{...},{...},...],
nextUrl: "url_goes_here";
}
The pages end when the nextUrl is null. I want to collect all the elements in data into one array while going through the paginated responses. I tried the following code segment.
const getUserData = async (url) => {
const result = await fetch(url)
.then(res => res.json())
.then(res => {
dataList= [...dataList, ...res.data];
console.log(res.data)
if (res.nextUrl !== null) {
getUserData(res.nextUrl);
} else {
console.log("else ", dataList);
}
})
.catch(err => {});
return result;
}
The console.log can print the result. but I want to get all the data to get into a variable that can be used for further processing later.
Your approach using recursion isn't bad at all, but you're not returning the chunk of data (there's no value returned by your second .then handler). (You're also falling into the fetch pitfall of not checking ok. It's a flaw IMHO in the fetch API design.)
There's no need for recursion though. I'd be tempted to just use a loop:
const getUserData = async (url) => {
const result = [];
while (url) {
const response = await fetch(url);
if (!response.ok) {
throw new Error("HTTP error " + response.status);
}
const {data, nextUrl} = await response.json();
result.push(...data);
url = nextUrl;
}
return result;
};
But if you want to use recursion:
const getUserData = async (url) => {
const response = await fetch(url);
if (!response.ok) {
throw new Error("HTTP error " + response.status);
}
const {data, nextUrl} = await response.json();
if (nextUrl) {
data.push(...await getUserData(nextUrl));
}
return data;
};
or
const getUserData = async (url, result = null) => {
const response = await fetch(url);
if (!response.ok) {
throw new Error("HTTP error " + response.status);
}
const {data, nextUrl} = await response.json();
if (!result) {
result = data;
} else {
result.push(...data);
}
if (nextUrl) {
result = await getUserData(nextUrl, result);
}
return result;
};

Async await does not wait for function to finish

I use fetch to get data for each element of an array. Those values are pushed into an array and I want to return the max of those values once all values are fetched.
For that I used a promise:
async function init() {
await maxWaste(nut0Codes).then(response => {
console.log(response);
});
}
function maxWaste(nutCodes) {
return new Promise(resolve => {
let waste = [];
nutCodes.forEach((element) => {
let query = queryMaxWaste(element);
fetch(address + encodeURIComponent(query))
.then(response => {
return response.json();
})
.then(response => {
waste.push(response.results.bindings[0].wasteGeneration.value);
console.log(waste);
});
});
let maxWaste = Math.max(waste);
resolve(maxWaste);
});
}
I am not sure where my mistake is but the resolve happens before the fetch is done :
I receive the zero from the console.log(response) and I don't know why it is not working.
Any advice would be appreciated!
If you're going to write code that uses async, you should actually leverage async. If this needs to be run synchronously-ish, you can await within a for loop. If you want them all to run simultaneously, use a map and Promise.all.
async function init() {
const response = await maxWaste(nut0Codes);
console.log(response);
}
async function maxWaste(nutCode) {
const waste = [];
for (const element in nutCode) {
const query = queryMaxWaste(element);
const response = await fetch(address + encodeURIComponent(query));
const json = await response.json();
waste.push(json.results.bindings[0].wasteGeneration.value);
console.log(waste);
}
const maxWaste = Math.max(waste);
return maxWaste;
}
You could also try writing it like this so that you don't wait for each response to complete before running the next fetch:
async function init() {
const response = await maxWaste(nut0Codes);
console.log(response);
}
async function maxWaste(nutCode) {
const waste = await Promise.all(nutCode.map(async element => {
const query = queryMaxWaste(element);
const response = await fetch(address + encodeURIComponent(query));
const json = await response.json();
return json.results.bindings[0].wasteGeneration.value;
}));
return Math.max(waste);
}

Return resolve-value from async function

In my project I use promise (code below), how it is possible, that promise still pending, when I used keyword await. Can someone help me figure out, what I'm doing wrong?
const getTs = async () => {
const response = await axios.get('...')
.then(res => res.data)
.catch(() => 'ERROR');
return response;
};
console.log(getTs()); // Promise { <pending> }
The await does only stop the execution of the async function body, nothing else. The caller is not blocked, the code is still asynchronous, and you get back a promise. If you want to log the result, you have to wait for it.
const getTs = () => axios.get('...').then(res => res.data).catch(() => 'ERROR');
getTs().then(console.log);
// ^^^^^
or
async function getTs() {
try {
const res = await axios.get('...');
return res.data;
} catch (e) {
return 'ERROR';
}
}
async function main() {
const response = await getTs();
// ^^^^^
console.log(response)
}
main();
getTs will be resolved once the request is resolved. So you have to await the response like :
const getTs = async () => {
const response = await axios.get('...')
.then(res => res.data)
.catch(() => 'ERROR');
return response;
};
getTs().then(response => console.log(response));

Categories

Resources