sugoke
March 6, 2021, 9:50am
1
Hi
Bit stuck here. I have an axios get request server side that works as the result is displayed in console.
Now I would like to get the result client-side which is returned as undefined. I presume it is a sync issue and I don’t understand what the best practice is between Promises, async/wait, futures…
Meteor.methods({
'eod_query': async function() {
const axios = require('axios').default;
await axios.get('https://eodhistoricaldata.com/api/eod/MCD.US', {
params: {
api_token: 'xxxxxx',
fmt: 'json'
}
})
.then(function (response) {
console.log(response);
return response
})
.catch(function (error) {
console.log(error);
return error
})
.then(function () {
// always executed
});
},
});
Client: (returns undefined)
Meteor.call(‘eod_query’, function (error, result) {
if(error){
console.warn(error);
}
console.log(result);
});
How can I wait for the result client side?
Looks like you’re returning in the first .then statement, but not to anything. So if you set the axios.get to a variable, you should be able to return that.
Something like this:
Meteor.methods({
'eod_query': async function() {
const axios = require('axios').default;
const response = await axios.get('https://eodhistoricaldata.com/api/eod/MCD.US', {
params: {
api_token: 'xxxxxx',
fmt: 'json'
}
})
.then(function (response) {
console.log(response);
return response
})
.catch(function (error) {
console.log(error);
return error
})
.then(function () {
// always executed
});
return response;
},
});
Otherwise, you could use the older pattern of defining your response outside of the function and setting it once you’ve got a response.
Meteor.methods({
'eod_query': async function() {
const axios = require('axios').default;
let eod;
await axios.get('https://eodhistoricaldata.com/api/eod/MCD.US', {
params: {
api_token: 'xxxxxx',
fmt: 'json'
}
})
.then(function (response) {
console.log(response);
eod = response;
})
.catch(function (error) {
console.log(error);
return error
})
.then(function () {
// always executed
});
return eod;
},
});
This is how I use it:
try {
return await axios.get(url).then(content => content.data);
} catch (error) {
throw {
code: error.code,
message: error.message,
responseStatus: error.response?.status,
url
};
}
1 Like
sugoke
March 6, 2021, 10:09am
4
thanks, however for some reason both still return undefined. Any idea why?
sugoke
March 6, 2021, 10:12am
5
Thank you, this has worked:
'eod_query': async function() {
const axios = require('axios').default;
try {
return await axios.get('https://eodhistoricaldata.com/api/eod/MCD.US', {
params: {
api_token: 'xxxx',
fmt: 'json'
}
}).then(content => content.data);
} catch (error) {
throw {
code: error.code,
message: error.message,
responseStatus: error.response?.status,
url
};
}
},
Note that in your code the variable url
is undeclared/undefined, which is used in the catch
block, so you may want to assign a value to it.
1 Like