Anticipating the completion of multiple observable subscription functions

Is there a way to replace and convert all words in an array using an object's method that returns an observable? I found a helpful solution on this post which uses bind to pass the correct value.

After all subscriptions are complete, I want to execute another function called task2(). How should I go about implementing this?

for(let word in this.words){
    var i = Object.keys(this.words).indexOf(word);

    this.convertor.get(this.words[i].value).subscribe( function (i, result) {
    this.words[i].value = result; 
  }.bind(this, i));
}

//task2() <--------- when all subscribe functions finished

Answer №1

Can you identify the data type of this.words? If it happens to be an array, iterating through its elements becomes much simpler... It seems like there is a peculiar approach being used in your code...

Furthermore, contemplate utilizing arrow functions as a replacement for frequent usages of bind(this). This practice contributes to enhancing the readability of the code.

A suggestion would be to refactor your existing code by implementing the use of forkJoin:

let streams = [];
for(let i = 0; i<this.words.length; i++){
    streams.push(this.convertor.get(this.words[i].value));
}

Rx.Observable.forkJoin(streams).subscribe((result) => {
    // At this point, 'result' comprises an array containing the outcome, arranged in the correct sequence (The initial outcome corresponds to the first stream, and so forth).
    for(let i=0; i<result.length; i++) {
        this.words[i].value = result[i];
    }

    task2();
});

Answer №2

A strategy I've devised involves creating a function that triggers another function only after a specified number of calls, similar to how Promise.all works.

Here is an example implementation:

  function executeAfterNthCall(callCount, callback)
    {
    var callIter = 0;
    return function()
      {
      callIter++;
      if(callIter === callCount) { callback(); }
      }
    }
var task2AfterLastCall = executeAfterNthCall(Object.keys(this.words).length, task2);

for(let word in this.words){
    var i = Object.keys(this.words).indexOf(word);

    this.convertor.get(this.words[i].value).subscribe( function (i, result) {
    this.words[i].value = result; 
    task2AfterLastCall();
  }.bind(this, i));
}

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 correct method for configuring access permissions?

I'm in the process of developing a user management system, but I keep finding myself having to check the user type for each router. router.get('/admin/settings', (req, res) => { if(admin) { //Proceed. } } router.get(&apo ...

The Tailwind preset is generating CSS code, but the webpage is not displaying the intended styles

Can anyone explain why the preset is generating CSS in the output file, but the styles are not displaying in the browser? When I manually write CSS in newstyle.css, it gets outputted to output.css and renders correctly in the browser. I attempted adding t ...

How to verify if an object is empty in an AngularJS expression

I need to display either a Login or Logout button based on the value of a $rootScope variable. Currently, only the Logout button is showing up in the li tag below. I have specific actions that should occur after certain events: After Logging In:- $root ...

Displaying JSON data on an HTML page

i am currently developing a web application and i am facing an issue with retrieving data from JSON files and displaying them in table format. The problem arises when i encounter a 404 error, as i am working locally using Node.js. Edit 1: upon checking ...

Exploring the use of jQuery/JS for parsing and working with JSON

Hi everyone, I need some assistance with displaying data from an array created by a PHP file using JS/jQuery. Currently, I am working on implementing a points system for ZetaBoards which you can check out here. The points will be shown below the user' ...

New to React and struggling with updating the DOM

Upon receiving a React project, I am faced with the task of performing a complex state update on my DOM. Here is how my component looks: /** @jsx jsx */ import { jsx } from '@emotion/core'; import { Typography } from '@material-ui/core&ap ...

Encountering the error message "Function.prototype.bind.apply(...) cannot be invoked as a constructor

I'm attempting to implement Controller Inheritance in AngularJS (1.6.9), but encountering an error in the console: Function.prototype.bind.apply(...) is not a constructor. Here's the snippet from the HTML file: <!-- Controller Inheritance --& ...

Utilizing a jQuery AJAX request to invoke a web method within a

My goal is to integrate jQuery mobile into an existing ASP.NET webform application. I am currently considering using pure HTML controls to create the jQuery Mobile page. I am aware that when making an AJAX call, I can access code-behind static web methods, ...

Sending numerous HTML forms using a sole submit button through AJAX

On my website, I have a page named publish.php where users can input details for each image they upload. Each image has its own form, but only one form is displayed at a time in a tabbed layout when the user clicks on the corresponding thumbnail. I want to ...

What is the method to trigger a function upon opening an anchor tag?

When a user opens a link in my React app, I need to send a post request with a payload to my server. My current strategy involves using the onClick and onAuxClick callbacks to handle the link click event. However, I have to filter out right-clicks because ...

Stay dry - Invoke the class method if there is no instance available, otherwise execute the instance method

Situation When the input is identified as a "start", the program will automatically calculate the corresponding "end" value and update the page with it. If the input is an "end", simply display this value on the page without any modifications. I am in th ...

Tips on populating the gap between dual cylinder meshes in Three.js

I'm working on a code that creates cylinders using a series of 3D vectors, but I'm encountering an issue with unsightly gaps between them: Does anyone have any tips on how to fill in these gaps in the latest version of three.js? Any help would b ...

Avoiding drag events in hammer.js until the previous event is finished

I've been working on a basic photo gallery that switches images during a drag event. However, I'm encountering an issue with the iOS7 browser where the drag event gets triggered multiple times when dragging left or right. I attempted to use a glo ...

Utilizing a GLTF asset as the main Scene element in a Three.js project

I'm struggling with incorporating a gltf model as the main scene in Three.js. Specifically, I have a gltf model of an apartment that I want to load from inside and not outside the apartment. I also need the controls to work seamlessly within the apart ...

ArangoDB's graph maxDepth setting causing excessive iterations

I am working on creating a substantial social network graph using ArangoDB. The database currently contains approximately 35,000 vertices connected by around 150,000 edges. Considering the extensive amount of data, I was looking to display only a portion ...

Is it possible to utilize useRef to transfer a reference of an element to a child component?

When I want to mount something into the element with id tgmlviewer, I call it a viewer object. This process works smoothly when there is only one component of this kind. import React, { useEffect } from "react"; import { Viewer } from "../.. ...

Update the input value with the selected option from the dropdown menu in Angular

How can I dynamically set the value of an input field based on the selection from a dropdown menu in Angular using Reactive Forms? Below is my HTML code: <nb-card> <nb-card-header> Services </nb-card-header> <nb-card-body&g ...

When using TypeScript with custom components as children in React, the `type` returned by React.Children is a string representing the function

It might sound a bit odd, or maybe I'm completely off track here. While going through some articles and React documentation on getting children and identifying specific child components using React.Component.map(), I ran into an issue with my custom c ...

Page freezing due to JQuery scroll event

I successfully implemented a trigger that checks if an element is within the visible viewport and added it to the scroll event. While this works smoothly on some pages, I noticed that on larger pages it causes the page to freeze. In Firefox, I experienced ...

Reorganizing the layout of a React grid in response to changes in screen size

Currently, I'm facing a challenge in creating a container for a React app that includes a Highcharts chart and three textboxes. My struggle lies in getting the three textboxes to adjust and rearrange beneath the chart component when resizing the scree ...