I am currently working on a project using MEAN Stack. For the Frontend part, I have to accomplish two tasks. Firstly, retrieve data from the backend using a promise and then reuse that data in another promise. It's essentially 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);
});
One issue I'm facing is that I require deviceId
for my second API call, but since promises are inherently asynchronous, I won't get it synchronously. How can I resolve this functionality?
Secondly, I noticed that the data obtained within my promises cannot be accessed outside of them. This seems to be due to the fact that deviceId = response.data
is just a reference. Once the scope of the response ends, the value in deviceId
disappears. How can I extract data from the promises or should I nest the second promise within the first one to make it synchronous and ensure constant access to the data?