Fetch API: get promisestate of response - javascript

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();

Related

Issue with axios request

I am having issue with getting my axios request to work. I am following pattern shown me in one of the Udemy courses. Interesting thing is that I can console.log data, but I can't return data, and save it to a variable. Any help would be appreciated.
Have a nice day!
const get = async () => {
const res = await axios.get(
"https://www.themealdb.com/api/json/v1/1/list.php?i=list"
);
return res;
};
async means your function returns an promise. Thats a basic fact
const get = async () => {
const res = await axios.get(
"https://www.themealdb.com/api/json/v1/1/list.php?i=list"
);
return res;
};
get().then(result => {
console.log(result);
})
Read about it: https://javascript.info/async-await
However you do not need async in this case because axios is already returning an promise
const get = () => axios.get("https://www.themealdb.com/api/json/v1/1/list.php?i=list")
You should return res.data
import axios from 'axios';
const get = async () => {
const res = await axios.get(
"https://www.themealdb.com/api/json/v1/1/list.php?i=list"
);
return res.data;
};
const print = async()=>{
const resp = await get();
console.log(resp);
}
print();

Use Async wait to let .then disappear

Request:
async await for this line: fetch(url).then(resp => resp.json())
So there shouldn't be any .then() calls anymore!
The original code:
const urls = [
'https://jsonplaceholder.typicode.com/users',
'https://jsonplaceholder.typicode.com/posts',
'https://jsonplaceholder.typicode.com/albums'
]
const getData = async function() {
const [ users, posts, albums ] = await Promise.all(urls.map(url =>
fetch(url).then(resp => resp.json())
));
console.log('users', users);
console.log('posta', posts);
console.log('albums', albums);
}
getData();
What i try in my JS:
const [ users, posts, albums ] = await Promise.all(urls.map
(url=>
resp = await fetch(url);
data = await resp.json();
));
I want the output is as same as the original code
Your function returns nothing, and is not marked async (which is required from any function using await). Furthermore, it's not cool to not declare variables.
const [users, posts, albums] = await Promise.all(urls.map(async url => {
const resp = await fetch(url);
const data = await resp.json();
return data;
}));
EDIT: also, what guest271314 said - need curlies now that the inner function is not a simple expression.

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);
}

struggle to wrap promise with async await

I got unexpected identifier but not sure what is the mistake. I'm using fetch which is already a promise.
async getUsers = () => {
const resp = await fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json())
return resp
}
getUsers().then(users => console.log(users))
Notice the position of the async keyword:
Not:
async getUsers = () => {
But:
getUsers = async () => {
Run:
getUsers = async () => {
const resp = await fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json())
return resp;
};
getUsers().then(users => console.log(users))
As per comments:
Should I chain then() in getUsers()? async/await suppose to eliminate then() am I right?
Yes, you can await any Promise. Or use both .then() sometimes and await at others (like does the code above). But you could just use async/await as well.
The example below uses no .then():
getUsers = async () => {
const resp = await fetch('https://jsonplaceholder.typicode.com/posts/1')
return resp.json();
};
(async () => {
// notice to use the await keyword, the code must be wrapped in an async function
const users = await getUsers();
console.log(users);
})();
Aside from the typo in the async word pointed by #acdcjunior, you're mixing async / await with the usual promise handling (.then()) which is not wrong but kind of defeats the point. Using only async / await would look like:
const getUsers = async () => {
const resp = await fetch('https://jsonplaceholder.typicode.com/posts/1');
return resp.json();
}
async function fetchUsers() {
try {
const users = await getUsers();
console.log(users);
} catch(err) {
console.log(err);
}
}
fetchUsers();
you have the syntax wrong:
const getusers = async () => {
...
}
const is optional
Your syntax of declaring your function is wrong, here's some explanation.
If getUsers is a method of a react component class the syntax should be :
getUsers = async () => {
const resp = await fetch(
'https://jsonplaceholder.typicode.com/posts/1'
).then(response => response.json());
return resp;
};
or :
async getUsers() {
const resp = await fetch(
'https://jsonplaceholder.typicode.com/posts/1'
).then(response => response.json());
return resp;
};
If it's outside of a react component class or in a stateless arrow function component you can use this syntax :
const getUsers = async () => {
const resp = await fetch(
'https://jsonplaceholder.typicode.com/posts/1'
).then(response => response.json());
return resp;
};
const getUsers = async () => {
try {
const resp = await fetch('https://jsonplaceholder.typicode.com/posts/1');
return resp.json();
} catch(e) {
console.error(e)
}
}
(async () => {
const users = await getUsers();
console.log(users)
})()
Use this, and run

fetch API not returning response

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

Categories

Resources