The initial function that gets executed in the lodash chain is tap()

When using lodash chain to perform actions synchronously, I encountered an issue where .tap() is executed before the desired stage. I have been unable to find a solution using promises. I expected lodash chain to ensure actions are carried out in a synchronous manner, with tap only executing after forEach completes.

const ids = [
      {
        "id": 1,
        "refs": [
          {
              "skuId": 693194,
              "sizeId": "12M",
              "colorId": "ROSE"
          },
          {
              "skuId": 693195,
              "sizeId": "14M",
              "colorId": "ROSE"
          },
          {
              "skuId": 973804,
              "sizeId": "6M",
              "colorId": "GREEN"
          }
        ]
       },
       {
        "id": 2,
        "refs": [
          {
              "skuId": 693174,
              "sizeId": "13M",
              "colorId": "RED"
          },
          {
              "skuId": 693995,
              "sizeId": "14M",
              "colorId": "BLUS"
          }
        ]
       } 
     ]
     
     let id = 1
     
     _(ids)
     .chain()
     .map(value => {
        id = _.result(_.find(value.refs, function(sku) {
                  return sku.colorId === 'ROSE' && 
                    sku.sizeId === '14M';
                                    }), 'skuId');
                                    
     })
     .tap(() => console.log('id: ', id))
     .value()
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

Answer №1

It seems like the usage of chain may not be correct - make sure to refer to the documentation, and don't forget to unwrap the value by calling .value() as shown in the example. The execution order of Tap is important.

let id = null;

_.chain(ids)
  .forEach(value => {
    id = _.result(_.find(value.refs, function(sku) {
      return sku.colorId === 'ROSE'
        && sku.sizeId === '14M';
       }), 'skuId');                                      
  })
  .tap(() => console.log(id))
  .value();

Understanding your intention fully might be challenging, but consider rewriting the code using map to eliminate the outer id:

const ids = [
  {
    "id": 1,
    "refs": [
      {
          "skuId": 693194,
          "sizeId": "12M",
          "colorId": "ROSE"
      },
      {
          "skuId": 693195,
          "sizeId": "14M",
          "colorId": "ROSE"
      },
      {
          "skuId": 973804,
          "sizeId": "6M",
          "colorId": "GREEN"
      }
    ]
   },
   {
    "id": 2,
    "refs": [
      {
          "skuId": 693174,
          "sizeId": "13M",
          "colorId": "RED"
      },
      {
          "skuId": 693995,
          "sizeId": "14M",
          "colorId": "BLUS"
      }
    ]
   } 
 ]

let val = _.chain(ids)
  .map(value => {
    return _.result(
      _.find(
        value.refs,
        sku => sku.colorId === 'ROSE' && sku.sizeId === '14M'
      ),
      'skuId');
  })
  .value();

console.log(val);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

You might need to make some adjustments to your code to achieve the desired outcome.

Answer №2

When you include a line to display the value of id within the map function, you will observe that the id variable gets assigned twice, with the second assignment being null which overrides the intended value.

const ids = [
      {
        "id": 1,
        "refs": [
          {
              "skuId": 693194,
              "sizeId": "12M",
              "colorId": "ROSE"
          },
          {
              "skuId": 693195,
              "sizeId": "14M",
              "colorId": "ROSE"
          },
          {
              "skuId": 973804,
              "sizeId": "6M",
              "colorId": "GREEN"
          }
        ]
       },
       {
        "id": 2,
        "refs": [
          {
              "skuId": 693174,
              "sizeId": "13M",
              "colorId": "RED"
          },
          {
              "skuId": 693995,
              "sizeId": "14M",
              "colorId": "BLUS"
          }
        ]
       } 
     ]
     
     let id = 1
     
     _(ids)
     .chain()
     .map(value => {
        id = _.result(_.find(value.refs, function(sku) {
                  return sku.colorId === 'ROSE' && 
                    sku.sizeId === '14M';
                                    }), 'skuId');
        // Include this line to check the value of id within the map function
        console.log('id (in map): ', id);
     })
     .tap(() => console.log('id: ', id))
     .value()
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

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

Determining block time based on block number within Polygon Mumbai Testnet

Is there a dependable method to identify the production time of a specific block in Polygon Mumbai Testnet using only its block number? I am unable to utilize an Api for this purpose and am seeking a more user-friendly computational solution. Any suggest ...

Tips for implementing conditional styling (using else if) in a react component

Currently, while iterating through a list of header names, I am attempting to change the CSS style of a react component based on three different conditions. I have managed to make it work for one condition, but I am facing challenges when trying to impleme ...

printer.printFile function is generating a blank output

Utilizing the compiler API for Typescript code generation, I encountered an issue where printer.printFile consistently outputs empty strings. Despite successfully using printer.printNode and printer.printList to print my AST, printer.printFile remains unco ...

Warning message regarding unhandled promise rejection in NestJS websockets

I've encountered a puzzling issue while attempting to integrate an 'events' module into my application to utilize websockets. Upon adding the module, an unexpected error surfaced: (node:59905) UnhandledPromiseRejectionWarning: Unhandled pro ...

What is the best way to import multiple classes from a module folder in Angular2 using TypeScript?

In my Angular2 application, I have organized my modules as follows: /app /content /models resource.ts container.ts entity-type.ts index.ts /services /whatever ...

Is there a type-safe alternative to the setTimeout function that I can use?

When running my tests, I encountered an issue with the setTimeout method making them run slower than desired. I initially attempted to address this by using "any" in my code... but that led to complaints from eslint and others. Now, I have implemented a ...

Obtain one option from the two types included in a TypeScript union type

I am working with a union type that consists of two interfaces, IUserInfosLogin and IUserInfosRegister. The TUserInfos type is defined as the union of these two interfaces. export interface IUserInfosLogin { usernameOrEmail: string; password: string; } ...

What is the purpose of the forwardRef function in React?

I've been working on creating a HOC (higher order component) that assists in conditional rendering. Here is the snippet of code I have so far: interface ConditionalProps { renderIf?: boolean } const ConditionalizeComponent = <Props,>( Origi ...

The BehaviorSubject will consistently emit identical values to each subscription

I am currently facing an issue with the BehaviorSubject where it emits a value for every subscription. This means that if I have, for example, 2 subscriptions to this.projectService.projectState$ streams using methods like async or tap, the projectState$ e ...

How to stop a method in Angular2 when a specific response is received?

I've been grappling with the idea of unsubscribing from a method in Angular2 once it receives a specific response. settings.component.ts Within my component, the method in question is connectToBridge, where the value of this.selectedBridge is a stri ...

Incorrect errors are displayed by VS Code in ts-node shell scripts

I came across an interesting article discussing running a TypeScript file on the command line, and while it seems to be functioning properly, I am encountering invalid errors in VS Code: https://i.sstatic.net/eis3X.png As seen in the terminal (bottom hal ...

Develop a wrapper for a function with multiple variations in TypeScript

Encountering an issue with the code below while attempting to create a proxy for a function with multiple overloads: // The target function function original (a: number): boolean; function original (a: string): boolean; function original (a: boolean): bool ...

Select the implied type from a resolved Promise type in Typescript

I am working with a function called getStaticProps in Next.js that returns a Promise, resolving to an Object with the following structure: type StaticProps<P> = { props: P; revalidate?: number | boolean; } To generically "unwrap" the type o ...

Functionality for communicating components is only operational on a single platform

I am looking to create a service that can notify my components when there are any changes to the 'idCustomer' property. These changes should trigger certain actions in different components. Currently, I am using console.log to check if the change ...

Using Angular 7 shared service to allow sibling components to exchange data between each other

In my Angular 7 application, I have two sibling components - a configurator component and a custom stepper component. The configurator component is responsible for fetching data from the API and performing calculations on it. I would like to display the ca ...

Comparing TypeScript's `return;` with `return undefined;`: which is better?

I encountered a strange behavior that is puzzling to me, and I'm not sure if there's a logical explanation for it. In TypeScript, the following code works perfectly: type UndefinedFunction = () => undefined; let uf: UndefinedFunction = funct ...

Steps for modifying the value of a field within an Angular formGroup

Is there a way to update the value of the "send_diagnostic_data" field in a separate function? private generateForm(): void { this.messageForm = new FormGroup({ message: new FormControl(''), date: new FormControl(new Date()), messag ...

Sending a Nan alert regarding a JSON attribute

I recently completed a project using Angular4 that involves connecting to a nodeExpressJS server to retrieve JSON data and update the object with new information. Below is the onSubmit function from the addemployeeform. onSubmit(formValue: any) { cons ...

Upon updating AngularFire, an error is thrown stating: "FirebaseError: Expected type 'Ea', but instead received a custom Ta object."

I have recently upgraded to AngularFire 7.4.1 and Angular 14.2.4, along with RxFire 6.0.3. After updating Angular from version 12 to 15, I encountered the following error with AngularFire: ERROR FirebaseError: Expected type 'Ea', but it was: a c ...

The global variable in TypeScript is not specified; it is initialized within the declaration `declare global{}`

In my TypeScript code, I'm facing a challenge when trying to add a global scope variable. In JavaScript (NodeJS), this process is straightforward: // index.js globalThis.helloWorld = 'Hello World!'; require('./log.js') // log.js c ...