Promise object not returning a value - javascript

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

Related

Return of validate function not working with axios

I am trying to make a form, where users can change their email address of the account. I want them to enter their password to validate them. So I have a function that is doing the email change, but before it calls the validate function. If the return value is true it goes on. If not an error appears. But when testing it with the correct credentials it always goes into the else although i get a valid axios response.
emailChange() {
if (this.validate() == true) {
var data = JSON.stringify({
email: this.email,
});
this.put(data);
} else {
this.error = "Falsches Passwort";
this.snackbar = true;
}
},
validate() {
var data = JSON.stringify({
identifier: this.loggedInUser.email,
password: "123456",
});
var config = {
method: "post",
url: "http://192.168.190.112:1337/api/auth/local",
headers: {
"Content-Type": "application/json",
},
data: data,
};
this.$axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.then(function () {
return true;
})
.catch(function (error) {
console.log(error);
});
},
The function return is not returning to validate. Axios is asynchronous and you need either a promise or a callback.
this.$axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.then(function () {
return true; // this does not return to validate(). it returns just here
})
.catch(function (error) {
console.log(error);
});
This is a way to implement it.
emailChange() {
this.validate((error, isValid) => {
if (isValid) {
var data = JSON.stringify({
email: this.email,
});
this.put(data);
} else {
this.error = "Falsches Passwort";
this.snackbar = true;
}
})
},
validate(callback) {
var data = JSON.stringify({
identifier: this.loggedInUser.email,
password: "123456",
});
var config = {
method: "post",
url: "http://192.168.190.112:1337/api/auth/local",
headers: {
"Content-Type": "application/json",
},
data: data,
};
this.$axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.then(function () {
callback(null, true);
})
.catch(function (error) {
callback(error);
});
}
I think you're misunderstanding the purpose of .then().
Creating a request isn't instant, and it's completion depends on the server you're requesting data from to send you back a response. Because of this, axios uses asynchronous code to give you a Promise that will resolve after the request is complete.
The callback within the .then() function is called whenever the request is resolved (which could take multiple seconds with a slow connection).
The callback that contains your return statement could be called multiple seconds after your validate function ends, which isn't what you want.
I'd suggest using async/await as an alternative.
Declaring a function as async makes it return a Promise no matter what, which is what you want, and await waits for a promise to resolve before continuing.
Here's a quick example
// This function returns a promise!
async validate() {
// axios.get() returns a promise, so we use await to wait until it's resolved
let response = await axios.get("url")
// return the data (this is not a promise)
// since the method is async, this will be automatically converted into a promise
// that will resolve when the method returns something
return response;
}
// you can only use "await" in async functions
async emailChange() {
// wait until this.validate() is finished before continuing
if(await this.validate() == true) {
// etc.
}
}
async/await is generally the preferred way to do this because it's much cleaner than chaining callbacks together with .then()
Hopefully this helps

how to get axios to return the object instead of promise

currently, my code is returning a promise I need it to return the object that It is getting from the API call, how would do that?
import axios from 'axios';
const baseUrl = 'http://api.openweathermap.org/data/2.5/weather?';
const getWeatherData = async (city,country) => {
// const result=await axios.get(`http://api.openweathermap.org/data/2.5/weather?q=${city},${country}&APPID=180941f68139fba12f166dc35d9b688b`)
// return result;
axios({
method: "GET",
url: `http://api.openweathermap.org/data/2.5/weather?q=${city},${country}&APPID=180941f68139fba12f166dc35d9b688b`,
})
.then((response) => {
return response.data;
})
.catch((error) => {
console.log(error);
});
}
export default getWeatherData;
try {
const response = await axios({
method: "GET",
url: `http://api.openweathermap.org/data/2.5/weather?q=${city},${country}&APPID=180941f68139fba12f166dc35d9b688b`,
});
return response.data;
} catch (err) {
console.error(err);
}
You can rewrite your axios call this way since your function is flagged as async.
async functions always return promises. Within async functions, you can use await infront of other async functions or functions that return promises.

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

Can't get data from fetch

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.

Getting chained Promise response

I'm having some problems getting a response from a chained Promise.
I have my component where the chain starts
component
componentDidMount = async ()=> {
try{
const products = await post('payments/getProducts', {});
console.log(products);
} catch(e) {
console.log(e)
}
}
This component calls my API helper:
async function post(url, data) {
token = null;
if (firebase.auth().currentUser) {
token = await firebase.auth().currentUser.getIdToken();
}
try {
const response = axios({
method: 'POST',
headers: {
Authorization: `${token}`,
},
data,
url: `${API_URL}${url}`,
})
return response;
} catch(e){
Promise.reject(e);
}
}
and my API Helper then calls a Firebase Cloud Function which calls Stripe:
paymentRouter.post('/getProducts', (req, res) => {
return stripe.products.list()
.then(products => {
console.log(products.data)
return products.data;
})
.catch(e => {
throw new functions.https.HttpsError('unknown', err.message, e);
})
})
Calling the function is no problem, and my Cloud Function logs out the product data, but I can't get the response to log in my API Helper nor my component.
Promise.reject(e);
That is completely senseless as it creates a new rejected promise that is not used anywhere. You could await it so that it gets chained into the promise returned by the async function, or you just return the promise from axios:
async function post(url, data) {
let token = null; // always declare variables!
if (firebase.auth().currentUser) {
token = await firebase.auth().currentUser.getIdToken();
}
return axios({
method: 'POST',
headers: {
Authorization: `${token}`,
},
data,
url: `${API_URL}${url}`,
});
}
Now the errors don't go into nowhere anymore and you can probably debug the problem :)

Categories

Resources