creating a promise within a .then() function to pass along for future use in a different function

Currently, I am utilizing a native script firebase plugin that requires the following function:

getCompanyValue() {
     var value;
     firebase.getValue('/companies')
         .then(result => {
             console.log(JSON.stringify(result));
             value = result;
             return result;

         })
         .catch(error => {
             console.log("Error: " + error);
             return error;
         });
     return value;
 }

When importing this function into another file and using it like so:

var companyValue = this.myFirebaseService.getCompanyValue();

The first time I run it, it returns 'undefined', but on subsequent runs, it returns the actual value.

My inquiry is how can I modify the firebase function to return a promise, allowing me to make my second statement wait for its completion?

Answer №1

The function in Firebase that you're talking about returns a promise. This is why you can utilize .then and .catch after invoking the getValue function.

If you modify the getValue() function to return the firebase promise, it will look like this:

getValue(){
  return firebase.getValue('/companies');
}

You can then call getValue() at any time, but make sure to execute the code only after the getValue() promise has been resolved. Here's an example:

getValue().then(function(value) {
  console.log(value);
});

If you're having trouble understanding this concept, I recommend learning more about promises here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

Answer №2

Upon receiving the result from the then block, you can initialize the variable myValue.

Here's an example:

var myValue;

function fetchValue() {
  return firebase.fetchData('/companies');
}

myValue = fetchValue().then(result => {
    const value = JSON.stringify(result);
    console.log(value);
    return value;
  })
  .catch(error => {
    console.log("Error: " + error);
  });
}

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

What is the reason behind TypeScript resolving a union type to an empty string in the presence of logical operators?

To prevent a null object error, I attempted to use logical operators. The object in question has attributes including a string and a union type. When I employed the "&&" operator to verify the object's existence, it resulted in evaluating the expressi ...

What are some ways to detect TypeScript type errors in the data of a Vue component?

Recently, I delved into Typescript development using Nuxt-ts and Vue 2. My goal was to steer clear of class-style components so I opted for the following approach. I created my Interfaces in a folder named /types. Whenever I needed to declare a type in a ...

Filling out a form within a webpage fetched through a DOMParser

Creating automation software in JavaScript using TamperMonkey. The script performs several AJAX requests that retrieve HTML to be parsed with a DOMParser. Is there a way to submit these forms without opening the newly retrieved HTML on the main page? ...

Storing JWT securely in cookie or local storage for a Node.js/Angular 2 web application

I've been researching how to save jwt tokens in either local storage or cookies but I'm having trouble finding clear instructions online. Can someone provide guidance on how to instruct the server to recognize a user for future sessions? //a ...

Can you interact with a node within an Electron application even if the node integration feature is not enabled?

I have an electron app created with vanilla electron. (using npx create-electron-app ......) Can I use const electron = require("electron"); with nodeintegration:true? The library I'm using does not support nodeintegration:true, but my scr ...

How can a function be properly exported and referenced within a user-defined class using the Ionic/Angular CLI version 5.4.16?

I recently delved into coding just a week ago and am currently working on incorporating two buttons into my Ionic app. The first button is meant to trigger an action sheet, while the second should activate an alert. I have been following the official Ionic ...

Deactivate a button when clicked on a card that has been mapped

After creating a card component and mapping through each card, I added an onClick function to disable the button of the clicked card. However, my logic ended up disabling all buttons instead. Here is the code snippet where I define the rendering of the UI ...

Using Vue to pass an array of rules to a child component

Currently, I am passing a set of props called "propSet" to a child component. These props are computed and detect an 'edit mode' boolean that changes accordingly. The "propSet" defines the following form input props: color, filled, dense, outlin ...

Typescript allows you to apply a filter to an array

Query: Is there a way to display a pre-selected item from my dropdown using its unique ID? Issue/Explanation: The dropdown options in my web service are dynamically fetched based on a user's ZipCode. For example, a Provider is displayed as {Pho ...

How can one ensure that the element declared in the "let" clause is displayed in an HTML Angular template?

I am working on a component that can render a mat-table. Each cell can have a specified value, or if it is present, the component calls an ngTemplateOutlet and passes it a rendering function obtained from the calling object. export interface ColumnConfig { ...

AngularJS routing creates a conflict with Express routing

Having an issue with routing in Express, specifically when using code like this: app.get("/profile/:param", function (req, res) It seems to be conflicting with the path routing in AngularJS. For example, when a view in Angular with a URL like /profile/so ...

What is the best way to change function.bind(this) to an arrow function in a react native application?

I am attempting to convert my function into an arrow function, but I keep encountering an error of undefined when passing props. <TextInput style={styles.input} value={formState.inputValues.title} onChangeText={textCh ...

The reactivity of a Vue.js computed property diminishes when it is transmitted through an event handler

Within my main application, I've implemented a Modal component that receives content via an event whenever a modal needs to be displayed. The Modal content consists of a list with an associated action for each item, such as "select" or "remove": Vue. ...

Evaluating an angular component with a unique custom form control integrated?

My Angular component is quite simple and looks like this: import { Component, Input, forwardRef, ViewEncapsulation } from "@angular/core"; import { NG_VALUE_ACCESSOR, ControlValueAccessor } from "@angular/forms"; export const ...

comparing caching with jquery deferred against promise

Currently, I have implemented code using jQuery Deferred and ajax to fetch data from a remote API, store it in localStorage, and retrieve it from there. However, this code has a bug where it doesn't display the data properly the first time it runs (re ...

Using Django to rewrite URLs and transferring a parameter through JavaScript

Following up on my previous question, I am facing a challenge in passing a parameter to a view that is only known after the JS executes. In my URLConf: url(r'^person/device/program/oneday/(?P<meter_id>\d+)/(?P<day_of_the_week>\ ...

Failed to send JSON data to WebMethod

I am encountering difficulties while attempting to send JSON to a WebMethod. I have provided the method I am using below. If there is a more efficient approach, please advise me. My goal is to store the JSON object in a database. JavaScript function TEST ...

Tips for accessing files following the transmission of a post request within the req.body

Encountering a problem where image uploads to an s3 bucket are not successful. The error message received is: API resolved without sending a response for /api/upload/uploadPhoto, this may result in stalled requests. The front end includes an input that ca ...

HTML and CSS site lacking responsiveness

I am new to HTML and I have created a page that looks good on desktop, but it is not responsive on mobile devices. Can someone please help me with my HTML and CSS code? .link-menu { color: black; } .topbar-p ...

A guide on using Sinon to mock a custom $http transform

Exploring the proper method for mocking an http post with a custom transform in Angular using the Sinon mocking framework. In my CoffeeScript Sinon unit test setup, I define mocks like this: beforeEach module(($provide) -> mockHttp = {} $provide.value ...