How to console.log the data properly with fetch? - javascript

What's the proper way of returning the data not the promise object as the code snippet below does?
const getData = async () => {
try {
const res = await fetch(API_ENDPOINT);
const data = res.json();
return data;
} catch (error) {
ToastAndroid.show(error, ToastAndroid.LONG);
}
};
console.log(getGeneralData());

Async Functions return a promise, you need to use :
getData().then(res=>console.log(res);

You can wrap your code in "self invoked" function (async function() {....})() and it allows you to use await for awaiting result of getData().
(async function() {
const getData = async() => {
try {
const res = await fetch(API_ENDPOINT);
const data = res.json();
return data;
} catch (error) {
ToastAndroid.show(error, ToastAndroid.LONG);
}
};
console.log(await getData());
})();

The async function is just syntactic sugar for a Promise. You can call the .then() method to handle resolving the promise.
const API_ENDPOINT = 'https://jsonplaceholder.typicode.com/posts/1/comments';
const getData = async () => {
try {
const res = await fetch(API_ENDPOINT);
return res.json();
} catch (error) {
ToastAndroid.show(error, ToastAndroid.LONG);
}
};
getData().then(data => console.log(data));
.as-console-wrapper { top: 0; max-height: 100% !important; }

Related

axios.get always returning a Promise<Pending> [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 11 months ago.
I found different solutions here, but none worked for me. I have this simple code:
const Element = () => {
async function getEndData() {
const data = (await getEnd());
return data;
}
}
const getEnd = async () => {
return await axios.get('http://localhost:8080/end').then(res => res.data);
}
And it always return a Promise "pending" with inside a [[PromiseResult]] with the value i need, when i call getEndData().
I tried also to call directly getEnd() removing the then(), returning only the data, but nothing. If i print res.data in console.log, it will return the right value i need.
this should work:
const Element = () => {
async function getEndData() {
const data = await getEnd();
return data;
}
}
const getEnd = async () => {
const response = await axios.get('http://localhost:8080/end');
return response;
}
I'm not sure you are doing it the right way. You can try this:
const Element = () => {
return async function getEndData() {
const data = await getEnd();
return data;
}
}
const getEnd = () => {
return new Promise((resolve, reject) => {
axios.get('http://localhost:8080/end')
.then(res => {
resolve(res.data)
})
.catch(err => {
reject(err);
})
})
}
Also, What is the use of element function if you are not returning anything.
your getEndData() in returning a promise . add await or then where ever you are receiving the getEndData() response .
// const Element = () => {
async function getEndData() {
const data = (await getEnd());
return data;
}
// }
const getEnd = async () => {
return await axios.get('http://localhost:8080/end').then(res => res);
}
async function callEndData(){
let x = await getEndData()
console.log(x)
}
callEndData()
since it is returning promise and you are not using await or then it is showing promise pending
why do you need Element() ?
In case you need to call ELement function and also wants the data part of response you can try like this .
const Element = async() => {
async function getEndData() {
return await getEnd();
}
let fromEndData = await getEndData()
return fromEndData
}
const getEnd = async () => {
return axios.get('http://localhost:8080/end').then(res => {
return res.data
});
}
async function callEndData(){
let x = await Element()
console.log(x)
}
callEndData()
in console.log(x) i am getting the value being passed .

How release Promise pending with async-await in react

my Code :
const attList = async (areaCode, cityCode) => {
const url = `http://api.visitkorea.or.kr/openapi/service/rest/KorService/areaBasedList?ServiceKey=${serviceKey}&contentTypeId=12&areaCode=${areaCode}&numOfRows=40&sigunguCode=${cityCode}&MobileOS=ETC&MobileApp=AppTest`;
try {
const {data:res} = await axios.get(url)
const list = res.response.body.items.item;
return list
} catch (err) {
console.log(err);
}
}
console.log(attList(1, 1))
on Console :
PromiseResult is Allright, but I don't know how release PromiseResult from Promise{}
Async functions always return a promise. If the return value of an async function is not explicitly a promise, it will be implicitly wrapped in a promise. Note: Even though the return value of an async function behaves as if it's wrapped in a Promise. resolve, they are not equivalent.
const attList = async (areaCode, cityCode, serviceKey) => {
const url = `http://api.visitkorea.or.kr/openapi/service/rest/KorService/areaBasedList?ServiceKey=${serviceKey}&contentTypeId=12&areaCode=${areaCode}&numOfRows=40&sigunguCode=${cityCode}&MobileOS=ETC&MobileApp=AppTest`;
const _url = 'https://jsonplaceholder.typicode.com/todos/1';
try {
const data = await axios.get(url);
console.log(data);
} catch (err) {
console.log(err);
}
};
attList(1, 1, null);
you didn't define serviceKey so I couldn't test it with your URL, but I assure you the syntax is just fine.

Using async await with axios

I've got a function that makes a call with axios and returns it:
const makeRequest = () => {
return axios.get('/data');
}
const printResponse = () => {
makeRequest()
.then((response) => {
console.log(response)
})
.catch((error) => {
console.log(error)
})
}
I'm trying to use async await to make this better and avoid using 'then'.
const makeRequest = async () => {
return await axios.get('/data');
}
const printResponse = () => {
try {
const response = makeRequest();
console.log(response)
} catch(error) {
console.log(error)
}
}
However, despite using await, makeRequest still returns a promise, so I have to end up using then in my printResponse function anyway. Am I not using this correctly?
"However, despite using await, makeRequest still returns a promise"
Yes, of course it does. async/await is just syntactic sugar for working with Promises. In particular, any function marked async will return a Promise - this is by design.
If you don't like using .then, you can just as easily use async/await to consume this promise:
const printResponse = async () => {
try {
const response = await makeRequest();
console.log(response)
} catch(error) {
console.log(error)
}
}

Receiving undefined when trying to set return value of await function as a constant

I'm trying to set a constant to an await function to get the return information from getInfo. I can console long the object before returning it. But when I try to console log the value in post I get undefined. What am I doing wrong?
router.post('/', function(req,res,next) {
(async function(){
const modifierInfo = await getInfo();
console.log("returns undefined", modifierInfo)
//do more with return info after
})().catch(next)
});
const getInfo = () => {
(async function(){
try {
const ps = new sql.PreparedStatement(pool);
const statement = await ps.prepare("selectQuery");
const result = await statement.execute();
const modifierInfo = await result.recordset[0];
await statement.unprepare();
console.log("returns object", modifierInfo)
return modifierInfo;
} catch (err) {
console.log(err)
}
})()
};
I think the issue is that getInfo itself needs to by async. try something like this:
router.post('/', async (req,res,next) => {
try {
const modifierInfo = await getInfo(req.body.groupID);
console.log(modifierInfo)
} catch(err) {
console.log(err)
}
});
async function getInfo(groupID) {
try {
const ps = new sql.PreparedStatement(pool);
const statement = await ps.prepare("selectQuery");
const result = await statement.execute();
const modifierInfo = await result.recordset[0];
await statement.unprepare();
console.log("returns object", modifierInfo)
return modifierInfo;
} catch (err) {
console.log(err)
}
};

Promising an async function

I have an array of objects that I'm looping over and calling a function with them as the argument. It's an async/await function, and I'd like to create a PromiseAll that resolves when all of the async/await calls have concluded. I've used an array map to convert them to promises, but the promises resolve instantly and don't wait until all await calls have been made.
async function runTest({_id, name, live, dev}) {
(async () => {
const browser = await puppeteer.launch();
try {
const page = await browser.newPage();
} catch(error) {
await browser.close()
} finally {
await browser.close()
return
}
})();
}
module.exports = (tests) => {
let testPromises = tests.map((test) => {
return runTest(test).then(function (res) {
return console.log(res, 'done')
})
});
Promise.all(testPromises).then((data) => {
console.log('Done resolving')
}).catch(function(err){
})
}
What is the correct way to guarantee that all of the array objects have passed through the function and completed processing before resolving the PromiseAll? I'm not hugely familiar with async/await.
You dont need an async IIFE as i already mentioned in comments. More over your code can be simplified like so:
async function runTest({_id, name, live, dev}) {
// we can have one try/catch since you close browser at any error
try{
const browser = await puppeteer.launch();
const page = await browser.newPage();
}
catch(error) {
return await browser.close()
}
}
module.exports = async (tests) => {
try{
const data = await Promise.all(tests.map(test => runTest(test)));
console.log('Done resolving')
}
catch(e){ console.log(e)}
}
I think you may be missing a return statement in runTest, though I don't know why you need the anonymous async function in the first place, like #TheReason mentioned:
async function runTest({
_id,
name,
live,
dev
}) {
return (async () => { // here
const browser = await puppeteer.launch();
try {
const page = await browser.newPage();
} catch (error) {
await browser.close()
} finally {
await browser.close()
return
}
})();
}
The straightforward approach:
function launch() {
return new Promise(function(resolve, reject) {
setTimeout(resolve, 5000, 'blast off!')
})
}
async function doSomething(id) {
const message = await launch()
return `${message} [${id}]`
}
let runs = [10, 20, 30].map(doSomething)
Promise.all(runs).then(function(values) {
console.log(values)
})
//outputs
[ 'blast off! [10]', 'blast off! [20]', 'blast off! [30]' ]

Categories