Diverse behaviors exhibited by an array of promises

I've developed a function that generates an array of promises:

    async addDefect(payload) {
    this.newDefect.setNote(payload.note);
    this.newDefect.setPriority(payload.priority);
    const name = await this.storage.get(StorageKeys.NAME);
    const movingFilesJob = this.cachedPhotoUrls.map(url => {
      const defectImage = this.newDefect.generateImageUrl(name);
      return this.file.moveImageToAppFile(url, defectImage.url);
    });
    await Promise.all(movingFilesJob);
    this.viewCtrl.dismiss(this.newDefect);
  }

Now, I want to move the creation of movingFilesFob to another class. So, I created the following function:

async persistPhotos(photoBuffer: string[], defect: Defect) {
    const name = await this.storage.get(StorageKeys.NAME);
    return photoBuffer.map(url => {
      const defectImage = defect.generateImageUrl(name);
      return this.file.moveImageToAppFile(url, defectImage.url);
    });
  }

When I try to replace the code, I'm encountering the error message:

Argument of type 'Promise[]>' is not assignable to parameter of type 'Iterable<{} | PromiseLike<{}>>'.   Property '[Symbol.iterator]' is missing in type 'Promise[]>'

In my function call, it looks like this:

async addDefect(payload) {
    this.newDefect.setNote(payload.note);
    this.newDefect.setPriority(payload.priority);
    const name = await this.storage.get(StorageKeys.NAME);
    const movingFilesJob = this.photo.persistPhotos(this.cachedPhotoUrls, this.newDefect);
    await Promise.all(movingFilesJob);
    this.viewCtrl.dismiss(this.newDefect);
  }

It's puzzling why the first example works fine while the second one doesn't. I tried assigning type :any to the return value but it didn't work during runtime.

Answer №1

Providing a direct response to the query at hand:

Why is it that the code functions correctly in the initial example but not in the subsequent one? I tried assigning type :any for the return, but it still doesn't work during runtime.

The issue lies in inadvertently altering the return type.

Initial Code Snippet:

const movingFilesJob = this.cachedPhotoUrls.map(...)

In this snippet, an array is being assigned to movingFilesJob.

Rectified Version:

return photoBuffer.map(...)

This modification generates an array of Promise objects from persistPhotos(), whereas the async keyword anticipates a singular Promise object instead of an array of them.

T.J. Crowder consistently offers valuable insights: As he highlighted, a straightforward solution involves awaiting the promises from the map operation as follows:

const movingFilesJob = await this.photo.persistPhotos(this.cachedPhotoUrls, this.newDefect);

Answer №2

Reposition Promise.all within the function's code block

async persistPhotos(photoBuffer: string[], defect: Defect) {
    const name = await this.storage.get(StorageKeys.NAME);
    return Promise.all(photoBuffer.map(url => {
      const defectImage = defect.generateImageUrl(name);
      return this.file.moveImageToAppFile(url, defectImage.url);
    }));
  }

Async functions always return a single Promise. Currently, you are returning an array of Promises which results in the function returning a single Promise containing an array:

const results = await persistPhotos(...);

as a result, results will hold an array of Promises. To obtain their results, you must:

const realResults = await Promise.all(results);

Alternatively, you can reposition Promise.all inside the function.

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

The issue in AngularJS 1.4 where the select element value is not binding due to a type mismatch

My ng-model has a value assigned to it, but it is not binding with the selected element. <select data-ng-model="myval"> <option value="? number:2 ?"></option> <option value="2" class="ng-binding">Value 1</option> <op ...

What is the process for adjusting the width of an element using JavaScript?

I have a unique bar with one half red and the other green. I am trying to subtract 1vw from the width of the red section. Unfortunately, using style.width is not yielding the desired result. See below for the code snippet I am currently using: //FIGHT do ...

Troubleshooting a cross-origin resource sharing problem in Express.js

I've set up Express as the backend for my client application, but I keep encountering an issue when trying to make a request to the GET /urls endpoint. The error message I receive is: Access to fetch at 'http://localhost:5000/urls' from orig ...

Adjust text size based on device orientation changes

I'm struggling to dynamically change the font size based on screen orientation and width. How can I adjust the font size when switching between landscape and portrait mode? I attempted using an event listener, but it's not updating the font size. ...

Determine the most recent API response and disregard any outdated responses from previous calls

I am currently working on a search page where the user can input text into a search box. With each character they enter, an ajax call is made to update the UI. However, I am facing an issue in determining the response from the last API call. For example, i ...

I'm having trouble assigning the data from my object to the setState in my React class component

class AreaChart extends React.Component { constructor(props) { super(props); this.state = { chartData: GRAPH_DATA, chartDataSelection: GRAPH_DATA.selection };} The GRAPH_DATA object contains all the necessary data for my Area Ch ...

Ways to deduce or implement intellisense for parameter types in overloaded functions

Currently, I am developing an Electron application where numerous events are being passed around with specific listeners assigned to each event. One example is BrowserWindow.on: Electron.BrowserWindow.on(event, listener) The event can take on values such ...

Exploring nested maps in JavaScript

I attempted to nest a map within another map and encountered an issue where the innermost map is being executed multiple times due to the outer map. The goal is to link each description to a corresponding URL (using # as placeholders for some links). Here ...

Error thrown: Unhandled Promise Rejection - The name 'ngForm' could not be exported

Having an issue with ngModel for data binding in my Angular app, getting an error saying ngForm not found. I've already included FormsModule in app.module.ts as shown below. The error disappears when I remove #grantAccessForm= "ngForm", but then the p ...

The importation of TypeScript source modules is not compiled accurately in the distribution folder

Currently, I am working on a REST API in TypeScript with the following structure: ├── dist │ ├── index.js │ ├── library.js ├── src │ ├── index.ts │ ├── library.ts ├── node_modules ├── package. ...

Proper method for incorporating loading and error messages with the help of useContext and react hooks

Currently, I have a context.js file that makes an ajax call and stores the data in an array to be shared across components. While adding some 'loading ...' text during the loading process using axios, I feel there might be a better way to handle ...

The SideNav SpyOn feature failed to locate the specified method

In the test project I am working on, there is a side navigation menu. I need to create a simple test to verify that when I click the button, the sidenav opens or closes. The AppComponent interacts with the sidebar through its dependency, sidenavbar. it(&a ...

What steps should I take to fix this Angular 8 error?

Encountered an issue in ../node_modules/@angular/http/src/backends/jsonp_backend.d.ts:1:28 - error TS2307: Module 'rxjs/Observable' not found. 1 import { Observable } from 'rxjs/Observable'; ~~~~~~~~~ ...

An error has occurred in Angular2 and Ionic 2, where there is a TypeError preventing the reading of the property 'addEventListener' in the InAppBrowser

When attempting to open a remote address in my app using the Cordova plugin InAppBrowser, I encountered an issue with the following code: import { Injectable } from "@angular/core"; import { HttpQueryService } from "./httpqueryservice"; import { ToastCo ...

Zurb Foundation's sections have a strange issue where navigating between them introduces unexpected whitespace

I'm feeling frustrated as I try to work with Zurb Foundation sections. I've updated to the latest version 4.3.1. Following the documentation provided here: but encountering strange behavior while navigating through results. Refer to the screen ...

Make sure to verify the existence of a value before attempting to render it in Angular 4

I am currently working on a project that involves Angular 4. Here is an example of the code I am using : <div *ngFor="let item of results"> <p> {{item.location.city}} </p> <p> {{item.location.country}} </p> </div> T ...

When should you use isRequired for PropType versus defaultProps in a React application?

I often find myself confused about when to use .isRequired versus .defaultProps={...}. I personally feel that I should avoid using isRequired, as it seems like creating a potential bug in the application. By using isRequired, it automatically removes the n ...

Master the Art of Crafting Unique URLs

I am developing a web page that requires me to call two queries, each requiring an ID. However, I'm unsure of the best way to pass these IDs in the URL. For instance, one query is for books and the other is for authors. Currently, I have considered tw ...

The object's value may be 'undefined' after utilizing a switch case to ensure it is not undefined

Before I encountered the error Object is possibly 'undefined'.ts(2532) at testObject["x"], I had used case "x" in testObject. Why did this happen? Should I create my own type guard for it? interface TestObject { a?: number; ...

Java Script Custom Print Preview: A unique way to showcase your content

Is there a way to create a custom print preview dialog similar to the browser's print preview using Java Script? I am working on a book reader application that requires customization of the print preview dialog for page counting, automatic pagination, ...