Tips for creating a successful synchronous workflow with Promises in AngularJS

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?

Answer №1

Here's a potential solution:

$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("Data successfully sent");
    return response.data;
}).catch(function(err) {
    console.log('An error occurred');
    console.log(err);
});

Answer №2

Take a look at this code snippet:

function fetchMobileDevices(action){
    $http.get(Config.apiurl+'/mobile/devices').then(function(response){
        action(response);
    }, function(response){
        console.log("Error");
        return $q.reject(response.data);
    });
}

function fetchLocationDevices(action, 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) {
        action(response.data)
    }, function (response) {
        console.log("got error response");
        return $q.reject(response.data);
    });    
};

function initiate(){
    fetchMobileDevices(function(response){
        var deviceId = response.data.devices[0].deviceId;
        fetchLocationDevices(function(response){
            console.log("Response: " +  response)
        }, deviceId);
    });
}

This code utilizes callback functions to handle HTTP requests. After completing the request, it returns the response value.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for selecting the right decorator for your space

I am working on developing a game that utilizes an AI. This AI's API consists of 3 methods implemented in an Angular Service Here is a simplified version of the code: app.service('AI', [function(){ return { offer: angular.noop, ...

What could be the reason why only my drawLine function is functioning correctly?

As I embark on learning canvas and its control, I've encountered an issue with my code. The drawLine function, which should draw a dot or line on the canvas when triggered by onMove, is not rendering anything on the canvas surface. Can someone please ...

The onClick function designed to trigger the Material UI dialog box is experiencing functionality issues

Is there a bug in the component? The material-ui dialog-box sometimes pops up on button click and shows the target value perfectly, but other times it doesn't. I am passing the value on the icon onclick event - (e) and using it in the onClick function ...

Tips for displaying content in a stacked format when hovering, similar to a list item (<li>), using jquery/javascript

I am attempting to display different content on hover over text, specifically listing various HTTP error codes. My setup includes 3 icons and text that will reveal specific content based on the text hovered over: success error blocked Below is the JS cod ...

Is it true that in the Angular4 Webpack Starter, tsconfig.webpack.json is specifically designed for webpack, whereas tsconfig.json is intended for all other purposes

Please take a look at this git repository for more information: https://github.com/AngularClass/angular-starter The Angular4 Webpack Starter includes 2 important files: tsconfig.json and tsconfig.webpack.json These files have different configurations ...

I need to retrieve data from two different databases. What is the best way to combine the code into a single function?

I am working on fetching data from 2 database sources and combining them to send the merged data to result.html function showResult(req, res){ var n = req.query.query mysql_conn.query('SELECT query_text FROM catalogsearch_query WHERE ...

Tips for incorporating Javascript to restrict scrolling to just one:

My HTML page includes a section for filter_options and content. The filter_options contains a list of options. I have set up scrolling functionality where scrolling vertically changes the horizontal scroll position of the options. However, this setup is al ...

Ways to implement Formik to output a boolean value?

Currently, I am facing an issue retrieving a value from Formik. While it works perfectly fine with a Textfield component, I am unable to fetch the value of my switcher (which is a boolean). The setup for my file and switcher looks like this: <div clas ...

I have encountered an issue with my rows breaking improperly when viewing them in a PDF format, particularly when I include a minus

Whenever I try to view my HTML page in PDF form, I encounter an issue. The problem arises when the numerical values are too large, causing a line break between the minus sign and the values. Here is an example of the HTML page which appears perfectly: ent ...

An error has occurred due to a state of 'pending' being asserted

My approach involves utilizing a combination of various stacks: Mocha – serving as the test runner Chai – an assertion library webdriverio – providing browser control bindings Selenium – offering browser abstraction and a running factory ...

Having a problem with the getLastRow() function because it is returning empty rows in the output, and I specifically need to

I'm having trouble with the getLastRow() function in my script. I want to retrieve the last row with data, but the script returns all rows because there are empty rows below the filled ones. How can I modify it to stop at the last row with data? The d ...

Placing a div over a JavaScript element

Is it feasible to overlay a div(1) with a background image on top of another div(2) that contains JavaScript (like Google maps API v3)? I have experimented with z-index without success, and I am unable to utilize absolute positioning because I depend on t ...

Can Angular handle properties containing hyphens within them?

As I embark on creating my first complete Angular application, I encountered an interesting quirk. The model I am working with has a data structure that looks like this: { id: "12345", host: { name: "someHostServer", ip-addresses: ...

Ways to align the label at the center of an MUI Textfield

My goal is to center the label and helper text in the middle of the Textfield. I managed to achieve this by adding padding to MuiInputLabel-root, but it's not responsive on different screen sizes (the Textfield changes size and the label loses its cen ...

Export the model group to GLB format and then import it into threejs. Can individual materials be added to the models within the model group afterwards?

Let's say I exported a model group named C, which includes two models: A and B. When exporting a GLB file using Blender, does the file contain labels for models A and B? Also, what code should be used to access model A within model group C and apply a ...

Creating a stunning display of six video textures on a cube through the power of three.js

My current project involves working with a video that has been segmented into six parts. Here is a screenshot of the input video. The goal is to project these 6 videos onto the six faces of a cube using JavaScript: <!DOCTYPE html> <html> &l ...

Mastering EmberJS 2.7: The Definitive Guide to Binding the 'disabled' Attribute for Buttons

Here is an official guide explaining how to bind a boolean property to the disabled attribute of an HTML element. However, it references a controller in the process. I have a button that, when clicked, transitions the route (it must be a button and not a ...

What is the best way to ensure that the vue template runs before the script?

While attempting to set up an ASCII camera using Vue, I encountered a problem trying to access the canvas from the template. In the bootCanvas() method, when attempting to access the canvas with this.context = this.$ref.canvas.getContext('2d'), a ...

Make sure the checkbox is selected when the page initially loads, and if the page is reloaded, it should

When the page loads, I need a group of checkboxes to be pre-checked. I have an onload script that automatically checks the boxes, but when I uncheck them and reload the page, they remain checked. How can I make the checkboxes remember their last state? T ...

Change the background every time the onClick function is triggered

I am looking to change the background color each time an onClick event occurs and remove the previous tab background. However, when attempting to do so, the previous onClick effect remains. Check out the Code Below <script type="text/javascript"> ...