How can I console log the promise result instead of the promise - javascript

I have routes set up for a local api. So I am trying to retrieve the api data console log just the data. But whenever I run my code it console logs the entire promise. Any ideas on how to help?
This is my code:
const onPageLoad = async () => {
const response = await fetch(`/api/project/projects`, {
method: 'GET',
headers: { 'Content-Type': 'application/json' },
})
if (response.ok) {
console.log(response.json())
} else {
console.error(err)
}
}
onPageLoad();
This is what shows in the console log:

You can await the promise from response.json() to get its value:
const onPageLoad = async () => {
const response = await fetch(`/api/project/projects`, {
method: 'GET',
headers: { 'Content-Type': 'application/json' },
})
if (response.ok) {
let value = await response.json();
console.log(value);
// potentially do something else with value
return value;
} else {
console.log('fetch() promise succeeded, but not with response.ok', response.status);
throw new Error(`Got status ${response.status}`);
}
}
onPageLoad().then(() => {
console.log('all done');
}).catch(err => {
console.log(err);
});

Related

React Native get return value of async function

I am trying to get pub locations data from MYSQL server and my fetch function works well. But after that, this try-catch block does not return anything. I also tried without try-catch block but it does not change anything
getPubsFromDatabase = async () => {
let response = await fetch(fetchDataUrl, {
method: 'POST',
headers:
{
'Accept': 'application/json',
'Content-Type': 'application/json',
},
});
try{
let json = await response.json();
console.log(json)
return json;
}
catch (error) {
console.log(error);
}
}
And here, I am trying to get the return value of the function. But in this version, I cannot even see any console.log output. What I mean by the version is, if I put 2nd line out of the async block without "await" keyword, I can see the console.log but I it gives "undefined" then.
(async () => {
const locationsData = await getPubsFromDatabase();
console.log(locationsData)
})()
You can use then and catch in the function fetch.
const getPubsFromDatabase = () => {
return fetch(fetchDataUrl, {
method: 'POST',
headers:
{
'Accept': 'application/json',
'Content-Type': 'application/json',
},
}).then(async (response) => {
const json = await response.json().then((data)=>{
return data;
}).catch((err)=>{
console.log('error from json method: ',err);
return { error: {
message: 'error from json method',
object: err
}};
});
console.log(json);
return json;
}).catch((error) => {
console.log('error from request: ', error);
return {
error: {
message: 'error from request', object: error
}
};
});
}
And when you use the method getPubsFromDatabase would be of the next way:
(async () => {
const locationsData = await getPubsFromDatabase();
console.log(locationsData);
})()
You can use Promise to return either result or error, In the example given below i have used axios library but you can also try same with fetch api
For Example
export const getData = () => {
return new Promise((resolve, reject) => {
const url = ApiConstant.BASE_URL + ApiConstant.ENDPOINT;
const API_HEADER = {
"Authorization": token,
};
axios
.get(url, {
headers: API_HEADER,
})
.then((res) => {
resolve(res.data);
})
.catch((error) => {
// handle error
reject(error);
console.log(error);
});
})
}
You can call the above function in component or screen like this:
getData().then(
(data) => {
}
).catch(
error => {
console.log(error)
}
)
I solved the problem by instead of returning the value from the function, I set the value inside the function. This seems to work now.
const [locationsData, setLocationsData] = useState();
getPubsFromDatabase = async () => {
let response = await fetch(fetchDataUrl, {
method: 'POST',
headers:
{
'Accept': 'application/json',
'Content-Type': 'application/json',
},
});
try{
let json = await response.json();
setLocationsData(json); // Here, I changed the value of the locationsData instead of returning
}
catch (error) {
console.log(error);
}
}
And to call the function:
useEffect(()=> {
getPubsFromDatabase();
},[])

trying to use the response.json in a second function to filter a specific result

import fetch from "node-fetch";
const URL_API = `https://jsonmock.hackerrank.com/api/countries?`;
async function getResponse() {
let response = await fetch(URL_API, {
method: "GET",
headers: {
"Content-type": "application/json",
},
})
.then((response) => {
return response.json();
})
.then((data) => {
console.log(data);
})
.catch((error) => {
// handle error
console.error(`The unknown error has occurred: ${error}`);
});
}
getResponse();
async function getCapitalCity(country) {
const data = await response.json(); //error mentioned here
for (let info in data) {
console.log(info);
if (info.name === country) {
return info.capital;
} else {
return -1;
}
}
}
console.log(getCapitalCity("Afghanistan"));
working on retrieving a json object. I am trying to use the response object from getResponse() in getCapitalCity() based on country entered (string). My problem is knowing how to use the response in the second function. currently get a promise rejected reference error: response is not defined. thank you in advance.
I have reorganized Your code and added different loops.
const URL_API = `https://jsonmock.hackerrank.com/api/countries?`;
async function getResponse() {
let response = await fetch(URL_API, {
method: 'GET',
headers: {
'Content-type': 'application/json'
}
})
try {
return await response.json();
} catch (error) {
// handle error
console.error(`The unknown error has occurred: ${error}`);
}
}
getResponse();
async function getCapitalCity(country) {
const dat = await getResponse();
const capital = dat.data.filter((item) => item.name === country).map(item => item.capital);
return capital;
}
getCapitalCity('Afghanistan').then(items => console.log('capital: ', items))

React.js - const in async becomes undefined

const test = order.restaurantId;
console.log(test); //here test == 3
const getAvailableHours = async () =>{
console.log(test); //test == undefined
await fetch(`API Address`, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
})
.then(response => {
return response.json();
})
.then(responseText => {
console.log(responseText);
})
.catch(error => {
console.log(error);
});
}
Hi, I am trying to fetch data from API by using restaurant ID but when I'm passing the ID to async it becomes undefined.
I am new in React.js, anyone has any ideas?
async await syntax allows you to avoid .then method, so you can handle promises with a more readable syntax. With try catch blocks you can handle errors, try this:
const getAvailableHours = async () => {
try {
let response = await fetch('https://api-address-goes-here/', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
let responseText = await response.json();
return responseText;
} catch (err) {
console.log(err)
}
}

How to return data from a fetch and use the data to another function

I want to use the data I get from a fetch request so I return it as an array. The return value(array) will be use to another function but I get a promise :
Promise {<pending>}
__proto__: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: Array(10)
Below is the complete code
function getEmailList() {
fetch(myData.root_url + '/wp-json/wp/v2/email', {
method: "GET",
headers: {
'Content-Type': 'application/json'
}
}).then(response => {
return response.json();
}).then(emails => {
emails.map((email) => {
emailArr.push(email.title.rendered)
})
return emailArr;
}).catch(err => console.log('failed', err))
}
function getData() {
let emailList = getEmailList();
console.log(emailList)
}
Your calling code can be
function getData() {
getEmailList().then(emailList => console.log(emailList));
}
Use async await
function async getData() {
let emailList = await getEmailList();
console.log(emailList)
}
You need to return fetch in getEmailList() and use async/await in getData().
function getEmailList() {
return fetch(myData.root_url + '/wp-json/wp/v2/email', {
method: "GET",
headers: {
'Content-Type': 'application/json'
}
}).then(response => {
return response.json();
}).then(emails => {
emails.map((email) => {
emailArr.push(email.title.rendered)
})
return emailArr;
}).catch(err => console.log('failed', err))
}
async function getData() {
let emailList = await getEmailList();
console.log(emailList)
}

Problem with promises and asynchronous operations

I have to make an HTTP POST request to the server, wait for the server response and then make another request (which will send some data of the server response back to the server). I thought it was an easy task and I did something like this:
const promise = new Promise((resolve, reject) => {
resolve(this.updatePU(name, 'text', selectedOption.code));
})
promise.then(() => {
console.log('Calling checkExpress function');
let express = '';
const puOrderNo = this.props.puOrderNo;
fetch('/CheckExpress', {
crossDomain: true,
method: 'POST',
headers: {
'Accept': 'text/xml',
'Content-Type': 'application/json',
},
body: JSON.stringify({"puOrderNo": puOrderNo })
})
.then(response => response.text())
.then(str => {
express = convert.xml2json(str);
}).then(() => {
const data = JSON.parse(express);
const checkExpress = data['elements'][0].elements[0].elements[0].elements[0].elements[0].text;
console.log('checkExpress:', checkExpress);
if(checkExpress === 'true'){
this.props.updatePackageTypeField(true)
} else {
this.props.updatePackageTypeField(false);
}
})
.catch(err => console.log(err));
})
The updatePU function is also an asynchronous function:
updatePU = (name, type, value) => {
const PUOrderNo = this.props.puOrderNo;
const updatedValue = type === 'text' ? (`'${name}': '${value}'`) : (`'${name}': ${value}`);
fetch('/ModifyPUOrder', {
crossDomain: true,
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
updatedValue: updatedValue,
puOrderNo: PUOrderNo
}),
})
.then(response => {
if(response.ok){
return response.json();
} else {console.log(response)}
throw new Error('Request failed!');
}, networkError => {
console.log(networkError.message);
})
.then(data => {
if ("error" in data) {
alert(data.error.message);
this.refresh();
}
this.props.updatePUOrderForm(data);
});
}
The result is that promise is ignored (I think) and the second request is made before the first one! I get that the problem is that the function that is resolved in promise is an asynchronous function as well but I am not sure what to do.
Any help would be much appreciated!
The primary problem is that updatePU doesn't return a promise. You should return the result of the promise chain by adding return in front of fetch:
return fetch('/ModifyPUOrder', {
Then in your code at the top, don't create a new promise, use the one from updatePU:
this.updatePU(name, 'text', selectedOption.code)
.then(() => {
console.log('Calling checkExpress function');
// ...
There's a second (largely unrelated) problem: You're converting network error (rejection) to a fulfillment:
.then(response => {
if(response.ok){
return response.json();
} else {console.log(response)}
throw new Error('Request failed!');
}, networkError => { // ***
console.log(networkError.message); // *** Converts rejection to fulfillment with `undefined`
}) // ***
Remember that every handler in the chain transforms what passes through it. A rejection handler that doesn't throw or return a promise that rejects converts rejection to fulfillment.
Rather than adding console.log to dump errors everywhere, just propagate the chain and, at the top level where you can't propagate the chain any further, just add a final .catch that reports/handles the error (which you do have in your first code block).
See *** comments for notes on that and a couple of other things:
updatePU = (name, type, value) => {
const PUOrderNo = this.props.puOrderNo;
const updatedValue = type === 'text' ? (`'${name}': '${value}'`) : (`'${name}': ${value}`);
return fetch('/ModifyPUOrder', {
crossDomain: true,
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
updatedValue: updatedValue,
puOrderNo: PUOrderNo
}),
})
.then(response => {
if(response.ok){
return response.json();
} // *** No console.log here
throw new Error('Request failed!'); // *** I wouldn't hide what happened, perhaps: `throw new Error("HTTP error " + response.status);`
}/* ***No rejection handler here */)
.then(data => {
if ("error" in data) {
alert(data.error.message);
this.refresh();
// *** You presumably want to return here or use `else` so you don't update the form below...?
}
this.props.updatePUOrderForm(data);
});
}

Categories