Uncertainty Surrounding the Functionality of Javascript's 'then' Method

Within my Angular controller, I have the following code snippet...

function performTask() {
  // Display the loading modal
  $scope.modal = $ionicLoading.show({
    content: 'Fetching current location...',
    showBackdrop: false
  });

  console.log("get orig pos");

  // Retrieve the initial position
  PositionService.getPosition(posOptions)
    .then(function(positionArr) {
      // First location obtained // this part does not run!
      console.log("got original pos: " + positionArr.length);          
      $scope.locationArray = positionArr;
      $scope.dataReceived = true;
      $scope.modal.hide();
    }, function(err) {
      // An error occurred
      console.log("something wrong in getPos");
      $timeout(function() {
        $scope.modal.hide();
      }, 3000);          
    });

    console.log("get next pos");

  PositionService.getPosition(posOptions)
    .then(function(positionArr) {
      // Second location obtained // this part executes!
      console.log("got new pos: " + positionArr.length);          
      $scope.locationArray = positionArr;
      $scope.dataReceived = true;
    }, function(err) {
      // An error occurred
      console.log("something wrong in getPos");
    });
 }

After running the program, I noticed that the PositionService.getPosition function is called twice as expected. However, only one of the then blocks is actually executed. Shouldn't both then blocks be invoked? Am I misunderstanding how this functions in Javascript? This is what the getPosition function looks like...

   getPosition : function(posOptions) {
      return $cordovaGeolocation
        .getCurrentPosition(posOptions)
        .then(function(position) {
          positionArr = positionArr.concat({
            position: position,
            status: 'new'
          });
          return positionArr;
        }, function(err) {
          console.log("PositionService: error getting position");
          return err;
        });
    },

UPDATE:

Here is the requested console output...

https://i.sstatic.net/bEa4K.jpg

Answer №1

For optimal performance, it is recommended to chain your calls to the position service like so:

var initialPosition =  LocationService.getCurrentPosition(options)
    .then(function(position) {
      // acquired initial location
      console.log("initial position: " + position.length);          
      $scope.locationData = position;
      $scope.dataReceived = true;
      $scope.modal.hide();
    }, function(error) {
      // error occurred
      console.log("error in acquiring position");
      $timeout(function() {
        $scope.modal.hide();
      }, 3000);          
    });

var updatedPosition = initialPosition.then (function() {
     return LocationService.getCurrentPosition(options);
   }).then(function(newPosition) {
      // obtained updated location
      console.log("updated position: " + newPosition.length);          
      $scope.locationData = newPosition;
      $scope.dataReceived = true;
    }, function(error) {
      // error occurred
      console.log("error in acquiring position");
    });

Answer №2

One of the callbacks in .then() is considered a 'success', while the other is labeled as an 'error'. Essentially, it's either one or the other. For example, an HTTP request can result in a status code of '200' for success or '404' for error.

For more information, check out:

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

Pass information to a JavaScript file without resorting to global variables

I am looking for a way to transfer information from an HTML page to a script file that is contained within the same page. My initial thought was to use a global variable defined in the page and then accessed in the script file. However, I understand that ...

Displaying placeholder text instead of actual input value

I need help figuring out how to make the input field display the placeholder text instead of the initial value from state. const initialState = [ { name: "Chris", age: 0, height: 0, weight: 0, }, ]; const [inf ...

Retrieving values from the parent state parameters

In my AngularJS app, I have set up the following structure: .state('people.view', { abstract: true, parent: 'people', views: { 'header@maincontent': { templateUrl: 'partials/people/_header ...

Utilizing AngularJS $anchorScroll for navigating to an anchor tag on a different page

On my AngularJS Home Page, I am trying to scroll to an anchor tag on another page. Both pages are loaded as partial html files into the ng-view component based on the URL. When I start the server, the home page loads and then I need to navigate to the FAQ ...

Getting the response from Google Cloud Translate API using Node JS

Recently, I've been experimenting with the Google Cloud Translate API in NodeJS. While I am able to successfully console.log the value returned from a promise, I am facing challenges passing that value into an EJS template file. Whenever I try to disp ...

Using Angular5 to extract coordinates from the Google Maps v3 API when a map "click" event occurs

Can anyone assist me with retrieving coordinates from a click event on a map? Here is the desired result: Link Below is the code I have so far: import { Component, OnInit } from '@angular/core'; import { ViewChild } from '@angular/core&ap ...

JQuery - Receive an error message when a value is missing

With my Website almost complete, I just need to add an error message for when a movie isn't found. I have an API that returns JSON and if someone enters an invalid movie like "ifeahaef," it returns null. Is there a way to use Jquery to display an erro ...

Receiving a JavaScript function's output with Python Selenium

Currently, I am in the process of scraping data from a specific webpage. The focus is on extracting the return string value from a Javascript function snippet. The target value to be extracted is indicated as "2227885" https://i.sstatic.net/5dLJ ...

"Encountered difficulty reading the data from the downloaded blob due to a problem

How can I check the internal buffer to see if my text data is present? Am I using node.js' Stream.read() correctly? I have a text file stored as a blob on azure-storage. After downloading the blob, I receive a readable stream along with information a ...

Ways to prevent the TAB key from automatically shifting focus to the next element after using scrollIntoView during page initialization in the Chrome browser

Encountering a strange issue specifically on the Chrome browser. After the page loads, I am using the scrollIntoView method in the ngAfterViewInit of an Angular component. When the page loads and scrolls to the element, everything appears to be functioning ...

Obtain personalized results for implementing in Convase JS from a PHP server

I have a table on my WordPress site with the following output: { { [line1]=> array(3) {{'x'=>'5' , 'y'=>'8},{'x'=>'5' , 'y'=>'8},{'x'=>'5' , &apos ...

Pressing the mouse on the div causes it to vanish until an animation is triggered

I am working with two objects: object1 and object2. object1 is set to have an animation delay of 0s object2 has an animation delay of 0.5s When you click on 1., both objects are assigned the class .animation, which works as expected. However, object2 wa ...

Adjusting the line-height in CSS dynamically based on the length of characters using jQuery

I am facing an issue with the Twitter widget on my website where our company's latest tweet sometimes gets cut off if it exceeds a certain length. I want to dynamically adjust the line-height CSS property of the element based on the tweet's chara ...

How is it possible for the zero value to still be submitted even after I have included display error messages?

I have written some code to display error messages in PHP, but it seems that the error message is not displayed when all fields are empty. This results in submitting empty values to the database. <!DOCTYPE HTML> <html> <head> <style ...

How can I include JavaScript files in Maya or 3DS Max?

My dilemma lies in attempting to access a js file on Maya (2013) and 3ds max (2016) without any available three.js importers for these particular softwares. How can I effectively import a js file on either Maya or 3ds max? Alternatively, are there other ...

Incorporating and utilizing a variable from a separate page in React Native

Screen 1 export class Register extends Component { constructor(props) { super(props); this.state = { number1=0 }; render() { const { number1 } = this.state; v ...

Using TypeScript with Vue and Pinia to access the store

Is it necessary to type the Store when importing it to TypeScript in a Pinia Vue project? // Component <p>{{ storeForm.firstName }}</p> // receiving an error "Property 'storeForm' does not exist on type" // Store ...

Creating a dropdown menu that functions for 24 hours non-stop by utilizing the Array.from( Array(n) )

Struggling to make my code less dense, I'm looking for the best way to implement a dropdown menu that allows users to choose between options 1-24 while the array is nested within an object. Thoughts? I'm working on a chrome extension that genera ...

Dealing with the information received from a PHP response during an AJAX request using JavaScript

Here is my PHP script <?php //establishing connection to the server //selecting the database $temporaryArray = array(); $counter = 0; $result = mysql_query("some query"); while($row = mysql_fetch_assoc($result)) { $temporaryArray["$counter"]= $row[" ...

Using jQuery, generate a dynamic form to create a multidimensional array

I've set up a form where additional dropdowns can be dynamically added if the user clicks on a specific link. Here's an example of how it looks: <div class="dynamic-sale"> <select name="sizes[]" id="sizes" class="entry-dropdown"&g ...