Search code examples
javascriptangularjspromisemeanjs

How to make a synchronous workflow work using Promises in AngularJS?


I am making a project in MEAN Stack. In Frontend I have to do two things. First get data from backend using a promise. and use that data again in another promise. basically something like this.

var deviceId="";
            deviceId = $http.get(Config.apiurl+'/mobile/devices')
            .then(function(response){
                deviceId = response.data.devices[0].deviceId;
                console.log(deviceId);
                return response.data;
            }, function(response){
                console.log("Error");
                return $q.reject(response.data);
            });
            console.log(deviceId);
            var postString = "AT+CGPSINF=0 0," + lat + "," + lng + ",847.413452,20150520205855.000,100,11," + velocity + ",0.000000 OK ,CRASH=0,"+deviceId;
 $http.post(Config.apiurl + '/device/locations', postString, { headers: { 'Content-Type': undefined}})
            .then(function (response) {
                console.log("Sent the data");
                return response.data;
            }, function (response) {
                console.log("got error response");
                return $q.reject(response.data);
            });

Now there is a conceptual problem that I need deviceId for my second API call and I won't get it synchronously, because promises are inherently asynchronous in nature. If I have to implement such a behavior. How do I go about it?
Second Ques. Whatever data I get inside my promises I am not able to get the same value outside the promise. That being said. I know that this must be caused because deviceId = response.data is a reference. So when response's scope ends.Value from deviceId is vanished. How do I get the data from the promises? or should I call the other promise inside the first one to make it synchronous and ensure that I always have the data?


Solution

  • Something like this should work

    $http.get(Config.apiurl+'/mobile/devices')
    .then(function(response) {
        deviceId = response.data.devices[0].deviceId;
        var postString = "AT+CGPSINF=0 0," + lat + "," + lng + ",847.413452,20150520205855.000,100,11," + velocity + ",0.000000 OK ,CRASH=0,"+deviceId;
        return $http.post(Config.apiurl + '/device/locations', postString, { headers: { 'Content-Type': undefined}});
    }).then(function (response) {
        console.log("Sent the data");
        return response.data;
    }).catch(function(err) {
        console.log('got an error');
        console.log(err);
    });