Transform a promise-based function into an observable stream

I'm looking for advice on how to convert a piece of code that uses and returns a promise into an observable.

Here is the original code snippet:

export const uploadMultipleFilesToAzure = (
  uploadData: Omit<UploadMultipleToAzure, 'id'>[],
  handleProgress: (
    loadedBytes: number,
    fileData: UploadMultipleToAzure['fileData'],
    uploadId: Upload['id']
  ) => void,
  individualCallback: Function
): Promise<BlockBlobUploadHeaders[]> => {
  // Code implementation here...
};

Answer №1

This appears to be a simple forkJoin scenario.

To put it simply, you can do the following:

const uploadMultipleFilesToAzure = (uploads: any[]) =>
  forkJoin(uploads.map(upload => 
    upload.somethingReturningPromise(prms)
  );

Instead of using Promises.all, you are now using forkJoin which takes promises as input and emits a single event with an array of results.

Where there was once a nested "then", you will now use xMap - let's say mergeMap. You need to convert from a promise to an observable using from():

const uploadMultipleFilesToAzure = (uploads: any[]) =>
  forkJoin(uploads.map(upload => 
    from(upload.somethingReturningPromise(prms)).pipe(
      mergeMap( ()=> individualCallback(uploadItem);
    )
  );

If you utilize forkJoin or from(), the promise will be invoked when the function to create the observable is called, rather than when the observable is subscribed to. It is recommended to use defer() instead for this reason:

const uploadMultipleFilesToAzure = (uploads: any[]) =>
  forkJoin(uploads.map(upload => 
    defer(() => upload.somethingReturningPromise(prms)).pipe(
      mergeMap( ()=> individualCallback(uploadItem);
    )
  );

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

Display the submission timestamp in Angular upon clicking the submit button

How can I capture the date and time when a user clicks the submit button in Angular? For example, if a form with name and email inputs is filled out and submitted, I want to display the date and time along with the name and email in a table. Here is some ...

Unable to allocate submit event category

This is a question about code and an error message. The code snippet is shown below: const handleSubmit = (e: React.FormEventHandler<HTMLFormElement>) => { // e.preventDefault() } <form onSubmit={handleSubmit}></form> Below is ...

What causes React JS to continuously render in an infinite loop when using hooks and useState

I am struggling with updating the current state of my component based on a result using a custom hook in React. Whenever I try to update it, I end up in an infinite loop rendering due to my usage of the useState() hook. I am still new to working with Rea ...

manipulator route in Nest.js

I have the following PATCH request: http://localhost:3000/tasks/566-344334-3321/status. The handler for this request is written as: @Patch('/:id/status') updateTaskStatus() { // implementation here return "got through"; } I am struggling t ...

The cautions of NPM CI and Bluebird assurances

Introduction: Our team has recently started using npm's ci command to ensure a more dependable installation of dependencies for our React application, as opposed to using install. However, we have encountered some unusual promise rejection behavior wh ...

Accessing object properties on the fly in TypeScript

I'm currently working on a TypeScript game that features an inventory system with various values, like so: export const Inventory = { food: 0, medicine: 0, rifleAmmo: 0, pistolAmmo: 0 } At the moment, I have a function in place to man ...

When viewing a React data table in Chromium browsers, the columns on the right side may flicker when the screen is small or the browser

I recently integrated the React data grid Npm package by adazzle. You can find more information about it here. I encountered an issue which you can see in this example: https://codesandbox.io/s/react-data-grid-example-9sb93?file=/src/App.tsx When using a ...

Encountering a non-constructor error while trying to import packages in React Typescript

I am currently working on a project that utilizes React with Typescript. While attempting to import a package, I encountered an error stating that the package lacks a constructor when I run the file. This issue seems to be prevalent in various packages, a ...

Using Typescript and Next.js to handle error messages returned from Axios responses

My Next.js application makes an API call to validate a registration form. The server returns error messages in the following format: {"message":"The given data was invalid.","errors":{"email":["The email has alr ...

Manipulate values within an array when a checkbox is selected or deselected

I am developing an Angular application where I have created a checkbox that captures the change event and adds the checked value to an array. The issue I am facing is that even if the checkbox is unchecked, the object is still being added to the array. D ...

Encountering issues with React Nextjs - unable to utilize useState hook or

Hi everyone, I'm new to React and I think I might have overlooked something. I've been trying to create a simple registration form, but it seems like I'm having trouble changing the state. ` import {useState} from 'react' export ...

Eliminate the loading screen in Ionic 2

Within my app, there is a button that triggers the opening of WhatsApp and sends a sound. Attached to this button is a method that creates an Ionic loading component when clicked. The issue I am facing lies with the "loading.dismiss()" function. I want the ...

Learn the process of transferring dropdown one component's value to another component in Angular

I'm facing an issue with removing the value of a dropdown from the table component to the ooptymodel component. Even after using input and output decorators, the solution doesn't seem to work. Can someone guide me on how to successfully remove th ...

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); ...

Receiving NULL data from client side to server side in Angular 2 + Spring application

I'm currently working on a project that involves using Angular 2 on the client side and Spring on the server side. I need to send user input data from the client to the server and receive a response back. However, I'm encountering an issue where ...

Library for Typescript on npm

My project involves a collection of base classes in TypeScript. Within a web application built with React and written in TypeScript, I am looking to integrate a library called 'Plain Old TypeScript objects', which defines all the data types. Let& ...

Error TS2307: Module 'bluebird' not located

Currently, my focus is on developing an app using Ionic 2 and Angular 2 along with Typescript. To incorporate messaging into my app, I opted to utilize the library amqp-ts. The installation of the library through npm was successful with the following comma ...

What are the appropriate Typescript typings for React Components that have the ability to return a string or their child components directly?

What are the suitable types for a React Component that can also output a string or directly its children, in addition to a JSX.Element? For example: type PropsStringExample = Readonly<{ returnString: boolean; }>; type PropsChildrenExample = Readon ...

Can you explain the variances between the two Pick<T,K> util type implementations?

Here is a link I am exploring: https://github.com/type-challenges/type-challenges/blob/master/questions/4-easy-pick/README.md I am struggling to grasp the distinction between these two code snippets: type MyPick<T, K> = T extends {} ? K extends keyo ...

The subscription for the second Observable in RxJS concatMap is triggered individually

I am currently developing an Angular 6 application. I want the app to display a loading animation whenever there is a change in the route or if there are any pending HTTP requests. To achieve this, I have set up two Observables as follows: For httpPendingR ...