Effect CommunityEC
Effect Community•3y ago•
5 replies
fawwaz

Understanding the difference between `Effect.map` and `Effect.flatMap`

hey all 👋 I need some help fixing my mental modle of Effect.map VS Effect.flatMap I hit a weird bug where my code didn't return error but also didn't run the way expected to do. The code below now is working as expected but in the pervious version I ahd used Effect.map (just below the comment line) and the database never updated. I know that there is limitation in the platform I'm using that un-awaited promises will be ignored but I don't see how would that be a problem with Effect.map ?

function updatePlacementDataAttribute(args: {
  ctx: MutationCtx;
  placementId: Id<"placements">;
  dataAttributeKey: string;
  dataAttributeValue: string;
}): Effect.Effect<never, UnExpectedError | PlacementNotFoundError, Id<"placements">> {
  return pipe(
    Effect.tryPromise({
      try: () => args.ctx.db.get(args.placementId),
      catch: () => new PlacementNotFoundError(),
    }),
    Effect.tap((placementId)=> Effect.logInfo(`result of getPlacement ${JSON.stringify(placementId)}`)),
    Effect.filterOrFail(Predicate.isNotNull, () => new PlacementNotFoundError()),
    Effect.tap((placementId)=> Effect.logInfo(`result of filtering ${JSON.stringify(placementId)}`)),
    Effect.map((placement) => {
      placement.data[args.dataAttributeKey] = args.dataAttributeValue;
      return placement;
    }),
    Effect.tap((placement)=> Effect.logInfo(`result of updating placement with new attribute ${JSON.stringify(placement)}`)),
    // Effect.map doesn't cause an error but also the operation doesn't run?
    Effect.flatMap((placement) =>
      Effect.tryPromise({
        try: () => args.ctx.db.patch(args.placementId, placement),
        catch: () => new UnExpectedError(),
      })
    ),
    Effect.tap((placementId)=> Effect.logInfo(`result of patch placement ${JSON.stringify(placementId)}`)),
    Effect.map(() => args.placementId)
  );
}
Was this page helpful?