Fulfill the promise within yourself as well

I am looking to create a custom promise and have attempted the code below. My challenge lies in retrieving the value of recommendationCacheUrls after the inner promise, specifically the fileTransfer.download promise, has resolved.

setNewCacheUrls(providedUrls: any, nativeURL: string): Promise<any> {
    return new Promise((resolve, reject) => {
    let recommendationCacheUrls = [];
    _.forEach(providedUrls, (url) => {
        const fileTransfer: TransferObject = this.transfer.create();
        fileTransfer.download(url.url, nativeURL + url.name).then((entry) => {
           recommendationCacheUrls.push({ name: url.name, url: entry.toURL() });
                }, (error) => {
            console.error('error: ' + error);
        });
    });
    resolve(recommendationCacheUrls);
});

}

Answer №1

If you want to achieve your desired outcome, you can utilize the power of Array map (or _.map if necessary) along with Promise.all

setNewCacheUrls(providedUrls: any, nativeURL: string): Promise<any> {
    return Promise.all(_.map(providedUrls, url => {
        const fileTransfer: TransferObject = this.transfer.create();
        return fileTransfer.download(url.url, nativeURL + url.name)
        .then((entry) => ({ name: url.name, url: entry.toURL() }));
    }));
}

_.map - This function generates a new array of values by transforming each value in the list - http://underscorejs.org/#map

Promise.all - This method returns a single Promise that resolves once all promises in the iterable argument have resolved or when there are no promises left in the iterable. It rejects with the reason of the first promise that rejects - https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

Essentially, the code maps providedUrls to the promise generated by fileTransfer.download ... .then, creating objects like

{ name: url.name, url: entry.toURL() }
.

Promise.all then waits for all these promises to complete before resolving to an array of those objects

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

Why has the need to import toPromise in Angular/rxjs vanished?

Many responses on Stack Overflow mention that to prevent issues like Error message: Property 'toPromise' does not exist on type 'Observable' in Angular, you are advised to import 'rxjs/add/operator/toPromise'. I followed t ...

The React component fails to load due to the discrepancies in the data retrieved from various asynchronous requests

Creating a travel-related form using React with TypeScript. The initial component TravelForm utilizes multiple async-await requests within useEffect hook to update the state of the subsequent component TravelGuideFields However, the values of props a ...

Challenges encountered when unit testing ngx-translate

0 I am encountering issues with unit testing while using the ngx-translate library. Despite adding a provider for TranslateService, the tests keep asking for more providers, creating an endless loop of dependencies. Specifically, I am trying to unit test ...

Tips for dynamically updating the included scripts in index.html using Angular 2

As I work on incorporating an Angular website into a Cordova app, one challenge I face is getting the Cordova app to load the Angular remote URL. The index.html file for the Angular site includes the cordova.js file, which is specific to each platform - ...

Add Lottie Player to Angular Installation

I've been attempting to integrate Lottie into my Angular web-app using the library found at Lottie. Unfortunately, I have encountered difficulties in doing so. Despite following the instructions provided on github, I keep encountering various errors, ...

Linking Ionic Apps to Different Subfolders

In order to redirect users to my ionic app instead of my website, I have successfully implemented universal links. However, the issue now is that all URLs within my domain (e.g. ) are being opened by the app. What I actually want is for only URLs from a sp ...

Firestore emulator outperforms Firestore in terms of performance

My application is capable of handling a substantial volume of write, read, and update operations (potentially exceeding 10000) under specific conditions. During the development of the app on a local environment, these operations usually complete within a ...

The 'toBeInTheDocument' property is not found on the 'Matchers<HTMLElement>' type

Having trouble setting up testing for a components library. Despite trying various examples and similar threads, I have not been successful. I can confirm that my setupTests.ts file is being loaded correctly (verified through a console.log). Additionally, ...

What are the best scenarios for implementing modules, components, or standalone components in Angular 17?

Apologies if this question has been posed before, but I'm still navigating my way through Angular and could use some guidance on when to utilize modules, components, or stand-alone components. For instance, if I am constructing a modest website consi ...

Creating a React component with a reference using TypeScript

Let's discuss a scenario with a reference: someReference; The someReference is essentially a React component structured like this: class SomeComponent<IProps> { getData = () => {}; render() { ...some content } } Now, how c ...

Using TypeScript with React Redux, encountering issue of property not being available in the Reducer from the ActionType

Currently, I am learning how to implement a Reducer in Redux while using React with TypeScript. I have encountered an issue that I need help with. Below are the action types that I am working with: import { LoginResponseInterface } from "../../interfaces ...

Looking to individually check each query parameter in Angular 6?

I'm currently struggling with managing query parameters in my Angular application. There are multiple query parameters on my search page with the following URL: /search?q=hyderbard&view=map&type=bat&brand=sg const urlParams = Observab ...

Purge the localStorage every time the page is refreshed in Angular 2

After successful authentication, I am storing a token in localStorage. However, every time I refresh the page, I need to delete the token and redirect to a specific router. I'm struggling to find a way to achieve this in Angular, so currently I' ...

You won't find the property 'includes' on a type of 'string[]' even if you're using ES7 features

I encountered a similar issue on another page where it was suggested to modify the lib in tsconfig.josn. However, even after changing compile to es7, the same error kept appearing and the project couldn't be compiled or built. { "compileOnSave": ...

Integrate Angular 2 components into WebStorm

I am currently working on a project using Angular 2 (rc5) and TypeScript (1.8.10). Angular 2 is built with TypeScript, but in the node_modules directory, I notice that there are JavaScript files (*.js) along with declaration files (*.d.ts). It makes it di ...

Utilizing Typescript's baseUrl compiler configuration for node development

Is there a way for node's module loader to support TS's baseUrl compiler option? With the introduction of the baseUrl compiler option in TS 2, project relative require() and import requests are now possible. However, this feature requires that ...

Using Angular to invoke a method from a subclass

I am currently utilizing a RAD software that automatically creates Angular code for me. Each time, it generates two components: one is the "generated" component and the other is an empty component where you can add your own custom functions. In this scen ...

`Planning the layout of an Angular application with distinct sections`

I've been working on breaking down my Angular app into separate sections and I have a few queries about how to proceed: auth login (only public page in the entire system, after login users are directed to either the admin or user portal based on ...

Angular: Navigating through two levels of fetched data from Firebase

I'm currently working on parsing retrieved data from Firebase within an Angular (Typescript) project. The structure of my JSON data in Firebase resembles the following: "customer" : { "customerId1" : { "documents" : { "documentId1" : { ...

Building a like/dislike feature in Angular

Here is a snippet of code I have that includes like and dislike buttons with font-awesome icons: <ng-container *ngFor="let answer of question.answers"> <p class="answers">{{answer.text}} <i class="fa fa-hand-o-le ...