This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I am trying to pass the array named 'sheetsArray' out of the code below so that I may utilize it for some tasks. I cannot for the life of me figure out how to do this, despite trying many things and googling for hours. I'm sure it's easy but I'm not even sure what I should be searching that I'm not.
var sheetsArrayOut = sheets.spreadsheets.get({
auth: googleauth,
spreadsheetId: outputDOCID,
}, function(err,response) {
if (err) {
console.log('ERROR:' + err);
return
}
var sheets = response.sheets;
if (sheets.length == 0) {
console.log('No data found.');
} else {
var sheetsArray = [];
for (i = 0; i < sheets.length; i++) {
sheetsArray.push(sheets[i].properties.title);
}
}
console.log(sheetsArray[4]); // this returns the sheet name
return sheetsArray;
});
console.log(sheetsArrayOut[4]); // this returns undefined
It returns undefined because I suspect the function is asynchronous. In this instance you can probably use a callback to good effect:
function getData(function (sheetsArray) {
// do things with sheetsArray
});
function getData(callback) {
sheets.spreadsheets.get({
auth: googleauth,
spreadsheetId: outputDOCID,
}, function(err,response) {
// do a bunch of things
callback(sheetsArray);
});
}
The first = in var = sheetsArrayOut = sheets.spreadsheets.get(...) is invalid syntax.
Use var sheetsArrayOut = sheets.spreadsheets.get(...) instead.
Why don't you just reassign the value at the end of the request
var sheetsArrayOut;
sheets.spreadsheets.get({
auth: googleauth,
spreadsheetId: outputDOCID,
}, function(err,response) {
//your functional code
sheetsArrayOut = sheetsArray;
});
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
How do I convert an existing callback API to promises?
(24 answers)
Closed 2 years ago.
I'm fairly new to JS, this being my first project in it (using sqlite and the twitter api). I've been stuck for a while now on this issue. I can get await and async to work fine in other test programs but when it comes to this one the await within the following function isn't waiting for getmin() to conclude before moving on, which is causing issues in my for loop.
In the same vein like I said this is my first js project, it's highly likely to be wildly unoptimised. If something stands out as inefficient to you let me know and I'll know for future what to do/avoid.
async function following(err, data, response) {
if (err) {
console.log(err)
} else {
for (let i = 0; i < data.users.length; i++){
let user = data.users[i]
userinfo.name = user.name
userinfo.screen_name = user.screen_name
userinfo.user_ID = user.id
maxparams.user_id = user.id
new_min_params.user_id = user.id
console.log(new_min_params)
x = await getmin()
console.log(x)
// T.get('statuses/user_timeline', maxparams, getmax)
// T.get('statuses/user_timeline', tweetparams, gettweets)
//databasedata = [data.users.screen_name, minTweetID, maxTweetID]
}
// console.log(response_dictionary)
// console.log("")
cursorscore = 0
}
function getmin() {
let sql = `SELECT MaxTweetID FROM following WHERE Handle = ?`;
db.get(sql, [userinfo.screen_name], (err, row) => {
if (err) {
return console.error(err.message);
} else {
return (row ? updatemin(userinfo.screen_name) : T.get('statuses/user_timeline', new_min_params, get_tenth_tweet))
}});
}
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
console.log() shows the changed value of a variable before the value actually changes
(7 answers)
Closed 5 years ago.
This is the sample code from Github. I am trying to geocode a user-submitted address and extract more information from by creating a function geocodeAddress (see the second block).
// Geocode an address.
googleMapsClient.geocode({
address: '1600 Amphitheatre Parkway, Mountain View, CA'
}, function(err, response) {
if (!err) {
console.log(response.json.results);
}
});
When I console.log the object it works but returns undefined. I have tried to initialize my object globally without success.
exports.geocodeAddress = function (address) {
var newGeocodedAddress = {};
googleMapsClient.geocode({ address: address }, function(err, response) {
if (!err) {
newGeocodedAddress.lat_lng = [response.json.results[0].geometry.location.lat, response.json.results[0].geometry.location.lng];
newGeocodedAddress.formatted_address = response.json.results[0].formatted_address;
newGeocodedAddress.place_id = response.json.results[0].place_id;
var address_components = response.json.results[0].address_components;
for (var i = 0; i < address_components.length; i++){
if ('locality' === address_components[i].types[0]) {
newGeocodedAddress.city_name = address_components[i].long_name;
}
if ('administrative_area_level_1' === address_components[i].types[0]) {
newGeocodedAddress.province = address_components[i].short_name;
}
if ('country' === address_components[i].types[0]) {
newGeocodedAddress.country_code = address_components[i].short_name;
}
if ('postal_code' === address_components[i].types[0]){
newGeocodedAddress.postal_code = address_components[i].long_name;
}
}
}
// console.log(newGeocodedAddress) returns the expected value
return newGeocodedAddress; // returns undefined
});
};
strong text
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I am trying to implement nested api calls in ionic3
submitLoginForm() {
var username = this.formData.value.username;
var password = this.formData.value.password;
var bodyjson;
var userId;
this.ApidataService.logincheck(username,password).subscribe(data => {
this.logindetail = data;
bodyjson = JSON.parse(this.logindetail._body);
userId = bodyjson.user.id;
if( userId != undefined){
this.ApidataService.userdata(userId).subscribe(data => {
this.userInfo = data;
});
}
console.log(userId);
});
console.log(this.userInfo);
}
Now when I call this function the nested api returns undefined for the first call and then from the second call onwards it returns proper values however when I try to log the argument that is being sent to the api I notice that the correct value is passed each time. I believe that this is due to some synchronization issues but am unable to figure out the issue and the solution for the same.
You can use flatMap here.It seems you don't need to retrieve results of both requests hence this should work for you.
import { Observable } from "rxjs/Observable";
import 'rxjs/add/observable/flatMap';
Then:
this.ApidataService.logincheck(username,password).flatMap(
(data) => {
this.logindetail = data;
bodyjson = JSON.parse(this.logindetail._body);
userId = bodyjson.user.id;
if( userId != undefined){
return this.ApidataService.userdata(userId);
}else{
return Observable.empty();
}
}).map((res: Response) => res ? res.json() : {})
.subscribe(data => {
this.userInfo = data ? data : {};
});
You can read more about flatMap here
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
why wont usernametoid function return anything? i know it exist by consoling it out, but it wont store in the otherplayerid variable? why?
my app: ( calling post api kill)
var userFunc = require('../factory/user_factory.js');
app.post('/api/kill', function (req, res) {
var username = "signature";//req.query.username;
var otherplayerid = userFunc.usernametoid(username);
if (!(otherplayerid)) {
console.log("other player is acually " + otherplayerid);
result.push("denne brukeren finnes ikke! " + otherplayerid);
} else {
}
});
and my user_factory:
var articles = require('../controllers/articles.server.controller'),
path = require('path'),
mongoose = require('mongoose'),
Article = mongoose.model('Article'),
Users = mongoose.model('User'),
errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller'));
exports.usernametoid = usernametoid;
function usernametoid(id) {
var query = Users.findOne( { username : id } );
query.exec(function(err, datas) {
console.log(datas._id);
return datas._id;
});
}
console:
other player is acually undefined
57c1c0f3b6b20c011242bf22
You need to read about asynchronous calls. Which is db request. Simple fix is callback:
function something(data, callback) {
return callback('some data from db')
}
something('x', function(cb) {
console.log(cb)
}
it is good practise to return two values (error, callback). But you can read it later on.
There are also promises. You can read about them insted of callbacks, but it is recommended to know both.
This question already has answers here:
Node.js - wait for multiple async calls
(5 answers)
Closed 7 years ago.
I'm trying to set some variables in node js like this:
var perm1 = 0;
var perm2 = 0;
check_tasksAssigned(data,function(resp1) {
perm1 = resp1;
});
check_projectMembers(data,function(resp2) {
perm2 = resp2;
});
if(perm1 && perm2) {
// do some db stuff here
}
But I'm getting as undefined. I also tried like this:
var perm1 = check_tasksAssigned(data,function(resp1) {
});
var perm2 = check_projectMembers(data,function(resp1) {
});
if(perm1 && perm2) {
// do some db stuff here
}
And have tried like this, but the result is same in all cases:
var perm1 = check_tasksAssigned(data);
var perm2 = check_projectMembers(data);
if(perm1 && perm2) {
// do some db stuff here
}
How do I solve this?
The best way is to use a promises library. But the short version might look like:
var perm1 = 0;
var perm2 = 0;
check_tasksAssigned(data,function(resp1) {
perm1 = resp1;
finish();
});
check_projectMembers(data,function(resp2) {
perm2 = resp2;
finish();
});
function finish() {
if(perm1 && perm2) {
// do some db stuff here
}
}
EDIT
By request, with promises, this code would look something like:
when.all([
check_tasksAssigned(data)
.then(function(resp1) {
perm1 = resp1;
}),
check_projectMembers(data)
.then(function(resp2) {
perm2 = resp2;
})
])
.then(finish);
But there are many ways of expressing this, depending on the exact promises library, etc.