Combining promises to handle the asynchronous promise received from this.storage.get() function

Struggling with managing asynchronous data retrieval from local storage in my Angular2/ionic2 app.

The code snippet I'm using:

  request(args) {
    var headers = new Headers();
    headers.append('Content-Type', 'application/json');

    // Retrieve token from local storage, add to header if available
    this.storage.get('token').then((value) => {
      headers.append('Authorization', 'Token ' + value);
    });

    args = args || {};

    var url = this.API_URL + args.url;
    var method = args.method;
    var data = args.data || {};

    var options = new RequestOptions({headers: headers, withCredentials: this.use_session});

    return new Promise((resolve,reject) => {

      if (method == 'GET') {
        this.http.get(url, options)
          .map(res => res.text())
          .subscribe(
            (data:any) => {
              resolve(data);
            },
            (err:any) => {
              data = {};
              data['status'] = 0;
              data['non_field_errors'] = ["Could not connect to server. Please try again."];
              data['error'] = err;
              reject();
            },
            () => {
            }
          );
      }
    });
  }

The code calling the request function:

  authenticationStatus(){
    return this.request({
        'method': "GET",
        'url': "/user/"
      })
      .then((data:any) => {
          console.log('****** authenticationStatus: GET /user/ SUCCESS');
      });
  }

And then it's triggered like this:

      this.djangoAuth.authenticationStatus()
        .then((data:any) => {
            this.loggedIn = true;
            this.enableMenu(true);
            this.root = PhotoPage;
          },
          (err:any)=>{
            this.loggedIn = false;
            this.enableMenu(false);
            this.root = LoginPage;
          });

Struggling with understanding nested promises and modifying the code to ensure that the result of this.storage.get("token") is added to the header before being used below. Need help with chaining promises effectively.

Answer №1

To successfully chain two promises, simply return the second promise within the callback passed to the first promise's then() method.

A more organized way to rewrite your code is by moving the header adding functionality to a separate function for better readability:

// Create and return a promise that resolves to headers
createHeaders() {
  var headers = new Headers();
  headers.append('Content-Type', 'application/json');

  // Get token from local storage if available
  return this.storage.get('token').then((value) => {
    headers.append('Authorization', 'Token ' + value);
    return headers;
  });
}

// Assemble request with proper headers
request(args) {

  return this.createHeaders().then(headers => {
    args = args || {};

    var url = this.API_URL + args.url;
    var method = args.method;
    var data = args.data || {};

    var options = new RequestOptions({headers: headers, withCredentials: this.use_session});

    return new Promise((resolve,reject) => {

      if (method == 'GET') {
        this.http.get(url, options)
          .map(res => res.text())
          .subscribe(
            (data:any) => {
              resolve(data);
            },
            (err:any) => {
              data = {};
              data['status'] = 0;
              data['non_field_errors'] = ["Could not connect to server. Please try again."];
              data['error'] = err;
              reject();
            },
            () => {
            }
          );
      }
    });
  });
}

Make sure you include all necessary return in your code implementation.

Additionally, consider handling non-GET methods by adding an else part with a reject:

if (method == 'GET') {
    ....
} else {
    reject(new Error('invalid method:' + method));
}

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

Error in Cross-Origin Resource Sharing (CORS) encountered when trying to

Below is the code snippet provided: app.js: const passport = require('passport') , FacebookStrategy = require('passport-facebook').Strategy , ... passport.serializeUser(function(user, done) { console.log('serializing user&a ...

Steps for converting an observable http request into a promise request

Here is a link to my service file: https://i.sstatic.net/8dsMx.png This is the TypeScript file for my components: https://i.sstatic.net/of6sx.png And these are the response models: https://i.sstatic.net/U8RUQ.png https://i.sstatic.net/7baTj.png I am curre ...

What is the best way to iterate over an Angular HTTP Response?

As a newcomer to Angular, I am working on mastering the process of uploading files and calling an API for validation. The API responds with a list of JSON validation errors based on specific file values. I am currently struggling to iterate through these ...

Are there any potential methods for converting HTML to PDF within a Cordova Angular JS and UWP app using jQuery? I encountered an error stating that 'blob:ms-appx-web' is not permitted to load

view image here I encountered this issue: SEC7134: Resource 'blob:ms-appx-web://mysiteurl/3d5c0f51-04e2-4944-bf3e-4ea19185511c' not allowed to load If anyone has a solution, please help us in resolving this problem. Below is my code snippet ...

Executing installed packages using npm: A step-by-step guide

Recently, I have encountered a confusing issue in my coding journey. In Python, I got used to installing packages and using them right away without any hiccups. For example, with SpotDL, everything worked seamlessly. However, things took a different turn w ...

Exploring Angular (5) http client capabilities with the options to observe and specify the response type as 'blob'

Situation: I'm facing a challenge in downloading a binary file from a backend system that requires certain data to be posted as JSON-body. The goal is to save this file using File-Saver with the filename specified by the backend in the content-disposi ...

invoking a method within an express route to retrieve and utilize middleware functions

For my project, I am working on a custom function to handle API request validation. Here is how it looks: export function validateBody(schema: string): (req: ExpressRequest, res: ExpressResponse, next: ExpressNextFunction) => void { return function ...

Using JavaScript to organize and categorize data within an array

I am working with a multidimensional array and need to filter it based on the value at a specific index position. Here is what the array looks like: arr = [ [1 , 101 , 'New post ', 0], [2, 101 , 'New Post' , 1], ...

Ways to Resolve the "TS2533: Object May Be Either 'Null' or 'Undefined'" Error on a Dynamic Object

I'm encountering an issue with the following code snippet: interface Schema$CommonEventObject { formInputs?: { [key: string]: Schema$Inputs; } | null; } interface Schema$Inputs { stringInputs?: Schema$StringInp ...

Switching to a different ion-tab in Ionic causes the history to be lost

While transitioning between pages with the ion-tabs directive, Ionic seems to forget the history. Can you provide a solution for this issue or identify the specific section of code that may be causing it? ...

NodeJS leverages IO threads for processing CPU tasks

When researching this topic on Google, I only found guides that explain how Node performs asynchronous operations with a single thread. However, this is not the information I am seeking. Imagine I have a blob that requires 5 minutes of CPU time to process ...

Shortcuts for $scope variables in AngularJS templates

Within my controller, I often set: $scope.currentThing.data For different parts of my template, sometimes I require currentThing.data.response[0].hello and other times currentThing.data.otherStuff[0].goodbye //or currentThing.data.anotherThing[0].goo ...

Exploring in Angular 2 by using First Name, Last Name, and Email for queries

Details Currently, I am working on implementing a search functionality using pipes. Users should be able to search by email, first name, or last name. At the moment, it only works for searching by email. I am looking to extend this capability so that user ...

AngularJS 1 scripts being compiled by Gulp in the wrong sequence

Have you ever encountered this issue before? Whenever I run my scripts through GULP, the console starts throwing errors, indicating that my directives and/or controllers are not being registered properly. To address this, I experimented by adding the app v ...

Encountered an error while attempting to update an object: Unable to read property 'push' of undefined

Encountering an issue while attempting to update an object with additional information, receiving an error message stating 'property \'push\' of undefined'. /*Below is the object model in question:*/ export class Students { ...

Using Mobile Phone Number and OTP for User Verification in the MEAN Stack

I'm new to the MEAN stack and I'm interested in implementing OTP authentication. I would like users to be able to register using their mobile numbers through OTP when they install my app. Is there a way to achieve this? Also, how can I create an ...

Error: passport-local-mongoose does not have a createStrategy or authenticate function

Currently, I am working on enhancing features of a starter project available at this repository. The specific task at hand involves integrating user login functionality using passport-local-mongoose. In my attempts to utilize different strategies for impl ...

Tips for resolving Typescript type error when overriding MuiContainer classes

My application is divided into two main files: (https://codesandbox.io/s/react-ts-muicontainer-override-yywh2) //index.tsx import * as React from "react"; import { render } from "react-dom"; import { MuiThemeProvider } from "@material-ui/core/styles"; imp ...

The issue with Rxjs forkJoin not being triggered within an Angular Route Guard

I developed a user permission service that retrieves permissions from the server for a specific user. Additionally, I constructed a route guard that utilizes this service to validate whether the user possesses all the permissions specified in the route. To ...

Is it necessary for Vue single file components (.vue files) to use `export default` or is it possible to use named exports instead?

export default may no longer be the recommended way to export modules, as discussed in these resources: After changing my Vue components from this: <script lang="ts"> 'use strict'; import {store} from '../../data/store' ...