What is the best way to implement a promise function in this scenario using JavaScript?

I am currently working on an app using AngularJS and the MediaFire JavaScript SDK to perform various tasks.

One specific task I am struggling with is creating a folder during an upload process, which returns a 'folderkey'. I would like to use .then in my service functions to maintain clean code in my controller while continuing with the file upload process.

Despite conducting research, I am still unsure about how to achieve this. An example in my context would greatly aid my understanding of the necessary steps.

Currently, I invoke this function in my service to create a folder:

mediafireService.createFolder('TestFolder');

I envision the implementation as:

 mediafireService.createFolder('TestFolder')
    .then(function(folderkey){
       //Upload file into that folder
    });

Below are my factory functions:

  function createFolder(folderName){

     var options = { foldername: folderName };

     login(function(){
       app.api('folder/create', options, function(data) {
         console.log(data.response.folderkey);
         return data.response.folderkey;
       });
     });

  }

   function login(callback){

     app.login({
       email: 'email',
       password: 'pass'
     }, callback);

   };

I am unsure if JavaScript supports this functionality natively or if an external service is required. I find myself a bit lost on this aspect at the moment.

Any assistance on this matter would be highly appreciated. Thanks.

Answer №1

Essentially, the issue lies in the fact that no promise is being created within the createFolder function of your service. To address this, you can construct a custom promise utilizing the $q dependency.

Within the method, return a deferred promise and resolve or reject it based on the responses from the server.

Service

function createFolder(folderName) {
  var deferred = $q.defer();
  var options = {
    foldername: folderName
  };
  login(function() {
    app.api('folder/create', options, function(data) { //success
      console.log(data.response.folderkey);
      //this line will resolve the promise
      //and send the folderKey to the consumer method.
      deferred.resolve(data.response.folderkey); 
    }, function(data) { //error
      //this line will reject the promise with an error message
      deferred.reject('error occurred');
    });
  });
  return deferred.promise;
};

Controller

mediafireService.createFolder('TestFolder').then(function(folderkey){
   //Upload file into that folder
}, function(error){
   //handle the 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

Issue: Dynamic server is experiencing abnormal increase in usage due to headers on Next version 13.4

Encountering an error in the following function. It's a basic function designed to retrieve the token from the session. 4 | 5 | export async function getUserToken() { > 6 | const session = await getServerSession(authOptions) | ...

Exploring the method of creating multiple nested states within various parent components while utilizing identical templates

I have developed a mobile site for purchasing, renewing, and transferring domains. The app consists of 4 templates that work together in a functional chain. Buy : Search -> (login if necessary?) -> Pay -> Confirmation Renew : Choose -& ...

This error occurs when trying to assign a value to a property of a variable that is currently undefined

Having some issues with assigning the latitude and longitude values to a variable in my code. I am able to retrieve them correctly, but when trying to use them in another method (onUpload()), I am facing some errors. export class latlonComponent implement ...

Delete the final comma in a JSON file using JavaScript so that it can be utilized by a Vue application

Using Axios in my Vue app, I am consuming a JSON file. The field "country" contains trailing commas which are creating issues. Here is the structure of the JSON: "country": "spain,france," .... "country": " ...

"Deploying code to Heroku using Node.js: A guide to adding git commits directly on

Currently, as I delve into learning Node and Git, I'm faced with a dilemma involving my Heroku app. The app is designed to interact with a local file on the server that serves as a basic JSON database. The issue arises when I attempt to manage this f ...

Focusing on maximizing the potential of individual elements within an array

I have an array of values and I am looking to create a new array where specific values are assigned based on the values in the original array. For instance: My initial array: var values = [1, 2, 3, 4] The new array I want: [red, green, blue, black] I ...

jQuery sidebar with a fixed position

Is there a way to implement a sidebar menu feature using jQuery that reappears on the left as the user scrolls down the page? You can see an example sidebar menu here. ...

Tips for maintaining accessibility to data while concealing input information

Is it possible to access data submitted in a form even if the inputs were hidden by setting their display to none? If not, what approach should be taken to ensure that data can still be sent via form and accessed when the inputs are hidden? ...

Firebase scheduled function continues to encounter a persistent issue with an "UNAUTHENTICATED" error being consistently thrown

I have created a firebase-function that is scheduled to retrieve data from an external API source and save it in Firestore. const functions = require("firebase-functions"); const admin = require("firebase-admin"); const { default: Axios ...

Making an AJAX request to a remote site through CORS while the rest of the page is utilizing the file:// protocol

When the page loads, it is loaded with: file:///opt/x/index.html. The index.html file contains AngularJS and UI-Bootstrap JavaScript and CSS files. It also has a variety of divs with Bootstrap columns and rows. The contents of index.html are as follows: ...

String values should determine whether a checkbox is checked or not

When retrieving data from LocalStorage, my code looks like this: angular.module('madMeApp').controller('campaignInDetails', function($scope) { var campaignToShow = JSON.parse(localStorage.getItem("CampaignDetails")); $scope.selecte ...

Binding hover and load events using jQuery on elements that are dynamically generated

One should note that the click event can be successfully bound to an element with the class name keybox, even if this element is dynamically generated. The code for this would look like: $('body').on('click', '.keybox', funct ...

Issue with React ChartJS rendering – Title not visibleWhen using React Chart

I'm currently using react chart js for displaying a doughnut in my component. "chart.js": "^3.7.1", "react-chartjs-2": "^4.1.0", However, I'm facing an issue where the title is not being displayed: const d ...

What causes an "Internal Server Error" when attempting to use data for a database request with AJAX GET/POST in Laravel?

There's a unique issue that I'm struggling to resolve... Every time I drag and drop an event into the calendar, an Ajax Post Request is sent to my controller. The controller then inserts some data into the database with the event name received v ...

The iframe is set to take the source URL from url.com/id using the "id" parameter

Currently, I am attempting to set the src of an iframe by extracting the URL from the toolbar address. The URL consists of the domain plus an ID, which happens to be the same as the YouTube ID. For instance: www.youtube.com/watch=id In my case, my domain ...

Excessive alerts being produced within the loop

I am trying to remove a wine from a JSON wine list and I want to display an alert if the wine doesn't exist in the JSON file. However, the alert is popping up for every entry in the list. I am struggling to find a way to use an if statement before pro ...

Tips for navigating to the top of the browser window from the middle or bottom using JavaScript in Protractor

I am in need of clicking the element positioned at the bottom of the page first and then I must click on an element located at the top of the page. In other words, scroll up where it is not visible to the browser. To scroll down, I have used: browse ...

Forwarding information and transferring data from a Node server to ReactUIApplicationDelegate

I am currently working on a NodeJS server using Express and React on the front-end. I am trying to figure out how to send data from the server to the front-end without initiating a call directly from the front-end. The usual solutions involve a request fro ...

Is there a way to display the output of jQuery in an input box rather than a span?

I need to display the result of this function in an input box instead of a span tag because I plan to utilize the result in the following form. function checkChange(){ $.ajax({ url: "ordercalculate.php", data: $('form').seria ...

A guide on how to identify the return type of a callback function in TypeScript

Looking at this function I've created function computedLastOf<T>(cb: () => T[]) : Readonly<Ref<T | undefined>> { return computed(() => { const collection = cb(); return collection[collection.length - 1]; }); } Thi ...