How to call then twice with same response object?
function a() {
return axios.get('/foo').then(function(resp){
// do something with resp, eg. if 401 then force local state to logout
})
}
// the caller:
a().then(function(resp) {
// not called, I want same resp, not just data
}).catch(console.log).then(clearLoadingBar)
If you want your promise to return resp, you will need return it:
return axios.get('/foo').then(function(resp){
// do something with resp, eg. if 401 then force local state to logout
return resp;
});
Related
I'm trying to create a function that parses a json when it gets passed a URL. It parses it and if I try to log it inside the request it works, but I cannot return this value.
function JaySon(){
request({url: url,json: true}, function (error, response, body) {
return body;
})
}
var url ="http://api.geonames.org/findNearbyPlaceNameJSON?lat=51.9877644&lng=-1.47866&username=demo";
var x = JaySon(url);
console.log("json:"+x);
The console just logs "json:undefined", from my understanding it is because console.log gets ran faster than the parsing finishes. How could I go about fixing this issue?
This is due to the fact that you're not returning anything in your function :
async function JaySon(url) {
return new Promise((resolve, reject) => {
request({ url: url, json: true }, function(err, res, body) {
if (err) reject(err);
else resolve(body);
});
});
}
use it like :
Jayson('your_url').then(data => data)
or with async/await, but then it has to be wrap inside an async function
Another possible reason may also be due to the fact that your function doesn't take any arguments thus there's no request made to the URL you have passed when invoking the function.
Your code should be something like
function JaySon(url){
request({url: url,json: true}, function (error, response, body) {
return body;
})
}
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
So I have a function that uses the refresh token I have to get a new access token and I want to use this function before every call that requires an access token.
The first function refreshAccessToken() makes the request and returns the response including the body that contains the new access token. Now I thought this was enough but I was getting undefined followed by the actual data and doing some digging I found this question:
Promise returns undefined
which led me to returning the value from this function so the promise resolves fully and using it in another, returnAccessToken().
returnAccessToken() is supposed to take the resolved promise value and return the access token but it behaves unexpectedly. The console.log line works like a charm and it logs the correct value everytime but when I return the token and try to use it in the function below it, it is undefined again.
api.js
"use strict"
const request = require("request-promise-native");
refreshAccessToken: async function (credentialsObject) {
const options = {
method: "POST",
uri: <refresh token uri>,
resolveWithFullResponse: true,
json: true
};
return await request(options);
},
returnAccessToken: function (auth) {
this.refreshAccessToken(auth)
.then(function (result) {
// This logs the result correctly
console.log(result.body);
return result.body;
}, function (err) {
console.log(err);
});
},
actionRequiringAccessToken: function (auth) {
let tokens = this.returnAccessToken(auth);
// This returns undefined
console.log(tokens);
}
index.js
Also yes I realize that logging here does nothing as I don't currently return a value I just include it because this is how actionThatRequiresAccessToken() is run in my setup.
"use strict"
const api = require("api");
let auth = {
// Credentials
};
api.actionRequiringAccessToken(auth)
.then(function (data)) {
console.log(data);
}, function (err) {
console.log(err);
}
Just add return in returnAccessToken method.. you are not returning anything
returnAccessToken: function (auth) {
return this.refreshAccessToken(auth)
return result.body;
That returns the data into the .then chain. So actually your method doesnt return anything. Might add a return here:
returnAccessToken: function (auth) {
return this.refreshAccessToken(auth) /*...*0
}
I would suggest make actionRequiringAccessToken async and drop returnAccessToken
actionRequiringAccessToken: async function (auth) {
let response = await this.returnAccessToken(auth);
let tokens = response.body //parse the response... whatever returnAccessToken does
console.log(tokens);
}
I'm experiencing a strange problem with meteor. I'm trying to make HTTP call an use the data in a React-Component. But I can't access the returned data.
on the server:
'get': function get() {
try {
const data = Meteor.http.get('url', {
params: {
"api_key": "key",
"attribute": "attribute"
}
}
return data.data;
} catch (exception) {
throw new Meteor.Error('500', exception);
}
},
on the client: i've set up a container using withTracker() so that i can access the http response as props in my react component.
export default withTracker(() => {
var data = [];
Meteor.call('get', function(error, success) {
if (error) {
console.log('error', error.reason);
}
if (success) {
data.push(success);
console.log('success', success);
}
});
return {
data,
};
})(Component);
I've tried all possible combination. Using arrays and objects, but none of them worked out. When using console.log(data), I get some data on the client. But using console.log(data[0]) return undefined.
I've also tried returning an object from the server 'get' method. An using js Object.assign. But when calling console.log(data.name) for example, I get undefined on the client.
Maybe I'm not solving it the right way, but I don't understand why this is always returning undefined when I tried to access the object's data.
Solved by calling putting Meteor.call in a component method, and passing another component method in the callback because Meteor.call does not support promises or async / await. reference
I'm working with Meteor and I'm trying to retrieve data from an external database (neo4j for that case).
My problem is when I Meteor.call() from the client to the server I need to have a return statement in the server function. But retrieving data from the database is async by itself.
This is a snippest of what I have:
client.js:
Template.test.created = function () {
Meteor.call('getData', id, function (error, response) {
if (response) {
console.log(response); //<-- reponse = "???"
}
});
}
server.js:
Meteor.methods({
"getData": function (id) {
neo.commit ( //<-- async function which expect a callback
id,
function(error, response) {
console.log(response); //<-- only here I have the response I want but now I cant "return" it.
return response;
}
);
return "???"; //<-- the actual return that is being send back
}
});
Any ideas?
You can use Future to fix your problem, Change your code to(it may need more changes depending on your code base):
...
var Future = Npm.require('fibers/future');
Meteor.methods({
"getData": function (id) {
var future = new Future();
neo.commit ( //<-- async function which expect a callback
id,
function(error, response) {
if (error) return future.throw(error);
return future.return(response);
}
);
return future.wait();
}
});
You can read more about Meteor's async patterns in the following links:
Async On Meteor Server
Meteor Async Guide
Meteor Patterns: Call an asynchronous function and use its returned value
Feel free to ask if you need further helps.
Similar issues have been posted, but none quite match what I've run into. I'm doing a simple POST to an internal server to get back product data. The call is successful and I see the JSON data correctly logging to my terminal when I do a console.log on the server side. The issue arises on the client side, when in the callback, the result and error both are undefined.
Server:
Meteor.methods({
ProductSearch: function(searchTerm) {
var method = 'POST';
var url = 'server';
var options = {
headers:{"content-type":"application/json"},
data: {
query:"trees"
}
};
return HTTP.call(method, url, options, function (error, result) {
if (error) {
console.log("ERROR: ", result.statusCode, result.content);
} else {
var txt = JSON.parse(result.content);
console.log("SUCCESS: Found "+txt.totalResults+" products");
}
});
}
});
Client:
Meteor.call('ProductSearch', searchTerm, function (error, result) {
if (error) {
console.log("error occured on receiving data on server. ", error );
} else {
var respJson = JSON.parse(result.content);
Session.set("productSearchResults", respJson);
}
});
When I log the values of error, and result on callback, they are both undefined, and I get the following error: Exception in delivering result of invoking 'ProductSearch': TypeError: Cannot read property 'content' of undefined
In your server-side method, you're not correctly returning the result of the HTTP.call, since you're using the asynchronous version, HTTP.call will return undefined and the result will only be accessible in the callback.
Use the synchronous version of HTTP.call instead and you'll be fine.
try{
var result = HTTP.call(method, url, options);
return JSON.parse(result.content);
}
catch(exception){
console.log(exception);
}
See the corresponding docs for HTTP.call for additional information.
asyncCallback Function
Optional callback. If passed, the method runs
asynchronously, instead of synchronously, and calls asyncCallback. On
the client, this callback is required.
https://docs.meteor.com/#/full/http_call