Failure to run angular-spotify method in Ionic service - javascript

I've been struggling with handling retrieval of Spotify data in an Ionic service all day, and something that was working earlier now suddenly doesn't.
I have my login script set up in a service, and it is all working fine. However, after the console.log('updateInfo() called'); method inside updateInfo, the program will skip the rest of the function, avoiding gathering the data from Spotify.
This is the entire service so far:
.factory('SpotifyService', function ($cordovaOauth, Spotify) {
var currentUser = {},
userId = '';
function login() {
console.log('login() called');
$cordovaOauth.spotify('583ac6ce144e4fcb9ae9c29bf9cad5ef', ['user-read-private', 'playlist-read-private']).then(function (result) {
window.localStorage.setItem('spotify-token', result.access_token);
Spotify.setAuthToken(result.access_token);
}, function (error) {
console.log("Error ->" + error);
});
}
function updateInfo() {
console.log('updateInfo() called');
Spotify.getCurrentUser().then(function (data) {
console.log('Gathering data');
currentUser = data;
userId = data.id;
console.log("CURRENT USER: " + userId + " - (" + currentUser + ")");
console.log('Done updating');
});
}
return {
getUser: function () {
console.log('SpotifyService.getUser() called');
var storedToken = window.localStorage.getItem('spotify-token');
if (storedToken !== null) {
console.log('Token accepted');
currentUser = updateInfo();
console.log('getUser function returns: ' + userId + " - (" + currentUser + ")");
//currentUser = Spotify.getCurrentUser();
} else {
console.log('getUser else accessed');
login();
}
return currentUser;
}
};
})
Any ideas as to why the Spotify.getCurrentUser() method won't run?

It seems like your issue is with promises. If Spotify.getCurrentUser() returns a promise you wouldn't know what the error is because you haven't defined a catch statement. You should read Promises in Angular Explained as a Cartoon for a simple and clear explanation of promises.
Revise your code to add a catch statement:
Spotify.getCurrentUser()
.then(function (data) {
...
})
.catch(function(error){
console.log(error);
});

Every time you use promises like $cordovaOauth.spotify() or Spotify.getCurrentUser() you have to define .catch block, that will help you debugging.
Add .catch block to the getCurrentUser() function call to track down your error and i would also recommend changing error callback pattern in auth function call into .catch block as well
.catch(function(error){
console.log(error);
});

Related

Why does Node style error 1st callback return undefined after callback

The following code is returning undefined when I attempt to execute the error, callback capability. I don't understand why the json isn't returning as the console log outputs the complete query.
Here is the invoked function that is producing the json into the log.
exports.getThem = (req) => {
var addy = req.body.email;
Picks.findOne({ 'email' : addy }, (err, theResults) => {
if (err) {
return ({ 'msg': err });
}
console.log("made the query " + JSON.stringify(theResults));
return theResults;
});
};
Above, theResults print "made the query " and a complete JSON string.
The invoking code will execute and return to Postman the following JSON without the theResults JSON.
The console.log "log this" never executes and the 2nd log prints "after the log" undefined.
{
"token" : someCrazyLookingToken
}
exports.loginUser = (req, res) => {
var theResults;
theResults = Picks.getPicks( req , ( err , thePicks) => {
console.log("log this" + JSON.stringify(thePicks));
if (!err){
console.log ("what happened" + err)
}
});
console.log("after the call " + JSON.stringify(theResults));
return res.status(200).json({ picks: thePicks, token: createToken(user) });
}
Why? Is there a timing issue I'm not waiting for in the callback?
It's not necessarily a timing issue, but perhaps a misunderstanding on your part in how callbacks work, particularly in their scope. In your code, theResults is never going to have a value.
Try setting it up like this, and read up on promises and callbacks to get a better understanding on both.
exports.loginUser = async (req, res) => {
try {
const theResults = await new Promise((resolve, reject) => {
Picks.getPicks(req, (err, thePicks) => {
if (err) {
return reject(err);
}
return resolve(thePicks);
})
});
return res.status(200).json({picks: theResults, token: createToken(user)});
} catch (err) {
//handle err
}
}

NodeJS - Callback Not executed

After I execute a function (getAvailableLabs) in this case - I want to either execute a callback or a promise. I'm not sure which I should be executing however I can't get either to work.
Routes:
router.get('/api/content_left', function(req, res, next){
const Labs = require("../models/Labs.js");
l = new Labs("Sample Lab", "Sample Description", "Sample Category", "Sample Tech");
l.getAvailableLabs(function(){
console.log("We made it here!");
});
console.log("This is post resposnse");
Labs.js:
getAvailableLabs() {
var d = db.any('select * from labs')
.then(data => {
console.log(data[0]);
return data
})
.catch(function (error) {
console.log(error + " - Error in function");
return error;
});
}
In the above case, it logs "end of available labs" followed by "this is post response". That's what I would expect with my understanding of callbacks. However it never executes "We made it here!" and I don't understand why? My impression is if I place a function within a function - it will be executed as a callback however this does not happen. Do I need return a specific way to execute a callback?
Thank you for your help.
Your getAvailableLabs function does not accept a callback parameter. I think it'd be best to stay consistent and use promises:
getAvailableLabs() {
return db.any('select * from labs')
.then(data => {
console.log(data[0]);
return data
})
.catch(function (error) {
console.log(error + " - Error in function");
return error;
});
}
...
l.getAvailableLabs().then(data => {
console.log("We made it here!");
});
If you'd like to use a callback instead of a promise here's how I'd write getAvailableLabs:
getAvailableLabs (callback) {
db.any('select * from labs')
.then(data => {
console.log(data[0]);
if (callback) { callback(null, data); }
})
.catch(function (error) {
console.log(error + " - Error in function");
if (callback) { callback(error); }
});
}
Calling this function:
getAvailableLabs((err, data) => console.log("We made it here!");

Socket.io emit not being called

I have this code here
io.on("connection", function(socket){
//other methods where emit works
socket.on("login", function(data) {
try {
pg.connect(conString, function(err, con) {
var query = con.query("SELECT * FROM accounts WHERE username" +
"='" + data.usn + "';");
query.on("row", function(row, result) result.addRow(row); });
query.on("end", function(result) {
if (sha512(data.pwd, result.rows[0].salt).hash ===
result.rows[0].password) {
socket.emit("loginResponse", { status: "Success" });
console.log("I GOT UP TO HERE WITHOUT EMITTING! WTF?");
console.log(sha512(data.pwd,result.rows[0].salt).hash);
console.log(result.rows[0].password);
}
});
});
} catch (ex) { console.log(ex); }
});
});
Obviously, on the client side, I have something like this:
socket.on("loginResponse", function(data) {
alert(data.status);
});
However, whenever I try to log in successfully, my server doesn't emit anything to the client, i.e. I will see the printed lines on my terminal but the client doesn't get a response from the server. I've been baffled by this. I have another function which touches the PostgreSQL driver and emits successfully, but this one doesn't. Does anyone know why this is the case?
You have a bug in your code. Asynchronous functions should never be written inside try/catch.
try {
setTimeout(function() {
do_something_that_throws();
}, 1000);
}
catch (e) {
alert("You won't see this!");
}
The problem is that the control flow leaves the try block before do_something_that_throws() gets executed, so the error thrown inside the callback never gets catched.
socket.on("login", function(data) {
pg.connect(conString, function(err, con) {
if(err) {
// handle error
}
var query = con.query("SELECT * FROM accounts WHERE username" +
"='" + data.usn + "';");
query.on("row", function(row, result) result.addRow(row); });
query.on("end", function(result) {
if (sha512(data.pwd, result.rows[0].salt).hash ===
result.rows[0].password) {
socket.emit("loginResponse", { status: "Success" });
console.log("I GOT UP TO HERE WITHOUT EMITTING! WTF?");
console.log(sha512(data.pwd,result.rows[0].salt).hash);
console.log(result.rows[0].password);
}
});
});
});
Try this approach and let me know if its working.

error using then and catch in angularjs

I am trying to create an user authentication using Flask as backend and AngularJS as frontend. But I'm stuck at this error. Below is the Angular code that I am using. The login function executes successfully but also throws the following error. Please help me in solving/figuring this issue.
'use strict';
var userModule = angular.module('userModule', ['userServices']);
userModule.controller('LoginController', ['$scope', '$location', 'userAuth', function($scope, $location, userAuth) {
$scope.login = function() {
console.log("username: " + $scope.email + ", password: " + $scope.password);
// userAuth.login($scope.username, $scope.password);
// initial values
$scope.error = false;
$scope.disabled = true;
// call login from service
userAuth.login($scope.email, $scope.password)
// handle success
.then(function () {
console.log('I am in then function');
})
.catch(function () {
})
};
}]);
Error
TypeError: userAuth.login(...).then(...).catch is not a function
at Object.$scope.login (http://localhost:5000/static/js/controllers/user.js:28:13)
at http://localhost:5000/static/lib/angular/angular.js:6365:19
at Object.Scope.$eval (http://localhost:5000/static/lib/angular/angular.js:8057:28)
at Object.Scope.$apply (http://localhost:5000/static/lib/angular/angular.js:8137:23)
at HTMLFormElement.<anonymous> (http://localhost:5000/static/lib/angular/angular.js:13159:11)
at http://localhost:5000/static/lib/angular/angular.js:1992:10
at Array.forEach (native)
at forEach (http://localhost:5000/static/lib/angular/angular.js:130:11)
at HTMLFormElement.eventHandler (http://localhost:5000/static/lib/angular/angular.js:1991:5)
and my login function
function login(email, password) {
// create a new instance of deferred
var deferred = $q.defer();
// send a post request to the server
$http.get('http://' + email + ':' + password + '#localhost:5000/api/login')
// handle success
.success(function (data, status) {
if(status === 200 && data.result){
// print response
console.log('Response: ' + JSON.stringify(data))
user = true;
deferred.resolve();
} else {
// print response
console.log('Response: ' + JSON.stringify(data))
user = false;
deferred.reject();
}
})
// handle error
.error(function (data) {
// print response
console.log('Response: ' + JSON.stringify(data))
user = false;
deferred.reject();
});
// return promise object
return deferred.promise;
}
I am tired of searching and figuring this issue but didn't find anything. Don't know what's wrong :/
Any help will be appreciated.
try this
userAuth.login($scope.email, $scope.password)
.then(function () {
console.log('I am in then function');
},
function(error){
console.log('Error', error);
})

How to break/return an Angular asynchronous call in AngularJS

I have the following project structure:
- PageController.js
- BusinessService.js
- NetworkManager.js
In my PageController I have the following call:
var getSomething = this._businessService.getMeSomething().then(function(response) {
alert("my response: " + response);
});
In my BusinessService:
getMeSometing: function() {
var user = this.getUserData();
if(user) {
var sendPromise = this._networkManager.getAnotherThing(user.id).then(function(response) {
alert("And another response: " + response);
});
} else {
$q.reject({ message: 'Rejecting this promise' });
}
},
The http calls are being made in the NetworkManager class.
So the problem here is that when I have no user data I want to break the call and so I'm using the reject.
This returns an error: Cannot read property 'then' of undefined regarding the call in PageController.
So, given my situtation, where if I have no userData, I want to cancel the request, how can I accomplish this?
Your call should return a promise. If there's a user, return the promise from getAnotherThing, otherwise, return the promise from $q.reject...
getMeSomething: function() {
var user = this.getUserData();
var sendPromise;
if(user) {
sendPromise = this._networkManager.getAnotherThing(user.id).then(function(response) {
alert("And another response: " + response);
// you probably want to return the data if successful (either response or response.data, depending on what response is)
return response.data;
});
} else {
sendPromise = $q.reject({ message: 'Rejecting this promise' });
}
return sendPromise;
}

Categories