Can't get data from fetch - javascript

I'm trying to make a fetch call and it works but when I try to get the result from another function I always get undefined.
This is my code:
const fetch_output = async (data) => {
await fetch("execute_command", {
method: "POST",
credentials: "same-origin",
headers: {
"X-CSRFToken": getCookie("csrftoken"),
"Accept": "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(data)
}).then(function(response) {
return response.json()
}).then(function(response) {
console.log(response)
//I get the correct response here
return response
}).catch(function(ex) {
console.log("Ha habido algĂșn error: ", ex)
})
}
const write_outputs = async () => {
for (const platform_id of platforms_ids) {
const data = {
platform_id:platform_id,
command:command
}
await fetch_output(data).then((resp)=>{
console.log(resp)
//I get undefined
})
}
}
write_outputs()
I've tried everything but I just don't know what am i doing wrong.

it is because an async function returns a promise that resolves to the returned value from the function
(async () => {})().then(value => console.log("value = ", value)); // undefined
(async () => {return 1})().then(value => console.log("value =" , value)); // 1
as you are not returning anything from fetch_output, it resolves to undefined
You should return from the fetch_output function instead of using await.
Also, because fetch is already a promise you can use a normal function instead of an async one

Because you call await fetch_output() you should not use .then() to retrieve its result. Drop the await.
Why? await replaces function().then().catch() with result = await function() in the way it handles a Promise or an async function. Use await or .then() but not both.

Related

Fetch request not returning any data in console, or on front end

When I submit my form, I am not returning any data, not even in my console. I am trying to return details from WHOIS regarding the URL that is searched, and am getting nothing back.
Can anyone provide any advice as to why this might be the case?
Here is my front end script tag, after my form:
document.getElementById('search').addEventListener('submit', function(e) { e.preventDefault(); getDetails(); })
async function getDetails(url = `http://localhost:3000/lookup/${url}`, data = {}) {
return new Promise(function (resolve, reject) {
fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'text/html'
},
body: JSON.stringify(data)
}).then(async response => {
if (response.ok) {
response.json().then(json => resolve(json))
console.log(data);
} else {
response.json().then(json => reject(json))
}
}).catch(async error => {
reject(error)
})
})
}
On my express backend I am using req.params.url if that helps provide any context at all...
My Status Code is 200, and all appears to be normal in the Headers tab...
You have a mix of promise and async syntax, which is confusing, let's translate it first by unpicking the promise and then into await (if you can use async then do, it's easer than Promise/then):
document.getElementById('search').addEventListener(
'submit',
function(e) {
e.preventDefault();
getDetails();
});
async function getDetails(url = `http://localhost:3000/lookup/${url}`, data = {})
{
// Fetch will throw an exception if it can't connect to the service
const response = await fetch(url, {
method: 'GET',
headers: { 'Content-Type': 'text/html' },
body: JSON.stringify(data)
});
if (response.ok)
return await response.json();
// We could connect but got an error back from the service
// There may not be a response body, so response.json() or .body() might crash
throw new Error(`Error from server ${response.status}: ${response.statusText}`;
// We don't need catch, as any exception in an await will cascade up anyway
}
This makes it much more readable, and it's apparent that getDetails doesn't make any changes itself, it just returns the JSON from the service. The fix needs to be in the event listener - it needs to do something with that result:
document.getElementById('search').addEventListener(
'submit',
async e => {
e.preventDefault();
const searchResult = await getDetails();
// Do something to show the results, populate #results
const resultsElement = document.getElementById('results');
resultsElement.innerText = JSON.stringify(searchResult);
});
You are mis-using async/await. Try this:
async function getDetails(url = `http://localhost:3000/lookup/${url}`, data = {}) {
const response = await fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'text/html'
},
body: JSON.stringify(data)
});
const json = await response.json();
if (response.ok) {
console.log(json);
return json;
} else {
throw new Error(json);
}
}
In essence await is a replacement for then (but you can only use it in functions marked with async).

javascript undefined value using fetch in function

If I call this function:
async function delete_get_note() {
let query = {
'command': 'delete_get_content',
'note_id': input_note_id.value
}
let response = await fetch(
'../api/api.php',
{
method: 'POST',
headers: {'Content-Type': 'application/json;charset=utf-8'},
body: JSON.stringify(query)
}
);
let result = await response.json();
log.innerHTML = result.log;
}
log displays the content of the json returned by my server. However, if I try to encapsulate the call to fetch in a function:
async function json_exchange(object) {
let response = await fetch(
'../api/api.php',
{
method: 'POST',
headers: {'Content-Type': 'application/json;charset=utf-8'},
body: JSON.stringify(object)
});
return await response.json;
}
And call:
async function delete_get_note() {
let query = {
'command': 'delete_get_content',
'note_id': input_note_id.value
}
let result = await json_exchange(query);
log.innerHTML = result.log;
}
Then log displays undefined.
What did I get wrong when I tried to put the call to fetch in a function ?
You forgot to add the parentheses to the json call:
return await response.json;
-->
return await response.json()
Tip: You can use TypeScript checking to easily detect such errors:

Vue - returning the result of a synchronous method

I'm struggling to return the synchronous results of the method below.
I call the method from a different method:
var result = this.getVendor(id)
console.log(result)
Here is the fetch method:
methods: {
async getData(id) {
const response = await fetch(`${API_URL}api/${id}`, {
method: "GET",
headers: {
authorization: `Bearer ${localStorage.token}`
}
})
.then(res => res.json())
.then(data => {
return data;
});
await response;
}
}
How do I return the results response of the getData() function to show in the console?
Async functions Always return a promise.
You can use the await syntax to return it properly.
async getData(id) {
const response = await fetch(`${API_URL}api/${id}`, {
method: "GET",
headers: {
authorization: `Bearer ${localStorage.token}`
}
})
const data = await response.json()
return data
}
You can access the data out of that function anywhere you call it.
let data = null
object.getData(2)
.then(x => {
data = x
})
Also if you are going to use async await make sure to use try and catch to handle any errors that come up.
async getData(id) {
try {
const response = await fetch(`${API_URL}api/${id}`, {
method: "GET",
headers: {
authorization: `Bearer ${localStorage.token}`
}
})
const data = await response.json()
return data
}
} catch(err) {
console.error(err)
}

Axios promise not resolving, always pending

I'm not sure but i cant get the life of me to get this to resolve. its always pending. I'm not the best with promises so please help me out.
export async function getQuotes() {
const options = {
headers: {
"x-rapidapi-host": API_URL,
"x-rapidapi-key": API_KEY,
"content-type": "application/x-www-form-urlencoded",
},
};
let res = await axios
.post(API_URL, {}, options)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
return res;
}
and this is how i'm calling it:
const new_data = dataApi.getQuotes();
console.log(new_data);
with the new_data variable, i'd like to access the data that was returned. I keep getting back pending promises instead.
In javascript, async functions return a promise that resolves to their return value. In order to access the data, you have to wrap it in another async function and call await or use .then:
// Either:
async function main() {
const new_data = await dataApi.getQuotes();
console.log(new_data);
}
// or
dataApi.getQuotes().then(new_data => console.log(new_data));
Read more here.
You can wait until the promise has been fulfilled and then process the data as follows:
dataApi.getQuotes()
.then(function(new_data) {
console.log(new_data);
})
.catch(function (error) {
// error handling
});
You should use async/await or promises (.then and .catch) - but not both at the same time. You should also know that an async function always returns a Promise, so you can use it with the then/catch syntax if you want.
// Call with the then/catch syntax
dataApi.getQuotes()
.then((data) => console.log(data))
.catch((err) => console.error(err))
// Is the same that this call with async await
async function main() {
try {
const data = await dataApi.getQuotes();
console.log(data)
} catch (err) {
console.error(err)
}
}
About your function, you're using async/await here. So you may not use then/catch but await in its body.
export async function getQuotes() {
const options = {
headers: {
"x-rapidapi-host": API_URL,
"x-rapidapi-key": API_KEY,
"content-type": "application/x-www-form-urlencoded",
},
};
try {
let res = await axios.post(API_URL, {}, options);
console.log(response);
catch (error) {
console.log(error);
}
return res;
}

Promise object not returning a value

I am trying to get the value of asset:
const asset = getAssetInformation(11002);
function getAssetInformation(id) {
return axios({
method: 'GET',
url: "/asset-information",
params: {assetId: id}
});
}
console.log(asset);
The result is:
[object Promise]
How do I get the returned value from the request?
Using async and await is a practical way -
function axios(query) { // fake axios, for demo
return new Promise (r =>
setTimeout(r, 1000, { asset: query.params.assetId })
)
}
function getAssetInformation(id) {
return axios({
method: 'GET',
url: "/asset-information",
params: {assetId: id}
})
}
async function main() { // async
const asset = await getAssetInformation (11022) // await
console.log(asset)
}
main()
// 1 second later ...
// { asset: 11022 }
You will need to use .then function.
const asset = getAssetInformation(11002)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Promises return another promise.
The way to unpack and work with a promise is through the .then() function, which will run after the promise returns.
const asset = getAssetInformation(11002);
function getAssetInformation(id) {
return axios({
method: 'GET',
url: "/asset-information",
params: {assetId: id}
});
}
Asset here is a promise, you want to use a then on it to get the value.
Instead of..
const asset = getAssetInformation(11002);
use
getAssetInformation(11002)
.then((response) => {
//What you returned will be here, use response.data to get your data out.
} )
.catch((err) => {
//if there is an error returned, put behavior here.
})

Categories

Resources