Rule chaining not working with Promise.all

Abierto
#303 1 comentario 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
4/5
Tiempo estimado
3-5 días
Aptitud para principiantes
35/100
Tipo de issue
Error
Claridad
Bastante claro
Estado de actividad
Estancado
Stack tecnológico
javascript
Área
backend

Línea de trabajo

Comienza reproduciendo el ejemplo de Promise.all del issue y, a continuación, inspecciona Engine.run y el manejo de runtime-fact utilizado por almanac.addRuntimeFact. Se considera terminado cuando las ejecuciones paralelas producen los resultados y eventos correspondientes para samuel, joseph y anthony, coincidiendo con el comportamiento secuencial.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

If I run the engine sequentially, I am getting the desired result. If I run it in parallel, I am getting results only for the first run.

student-fav-subject.js

const { Engine } = require("json-rules-engine");

const apiClient = require("./student-api-client");

let engine = new Engine();

async function start() {
  let mathematicsSubjectRule = {
    conditions: {
      all: [
        {
          fact: "student-information",
          operator: "contains",
          value: "Mathematics",
          path: "$.subjects",
        },
      ],
    },
    event: { type: "studies-mathematics" },
    priority: 10,
    onSuccess: async function (event, almanac) {
      almanac.addRuntimeFact("studiesMathematics", true);
    },
    onFailure: function (event, almanac) {
      almanac.addRuntimeFact("studiesMathematics", false);
    },
  };
  engine.addRule(mathematicsSubjectRule);

  let physicsFavoriteRule = {
    conditions: {
      all: [
        {
          fact: "studiesMathematics",
          operator: "equal",
          value: true,
        },
        {
          fact: "student-information",
          operator: "equal",
          value: "Physics",
          path: "$.favoriteSubject",
        },
      ],
    },
    event: {
      type: "physics-favorite-subject",
      params: {
        message: " has Physics as their favorite subject",
      },
    },
  };

  engine.addRule(physicsFavoriteRule);

  engine.addFact("student-information", function (params, almanac) {
    console.log("loading student information...");
    return almanac.factValue("studentName").then((studentName) => {
      return apiClient.getStudentInformation(studentName);
    });
  });

  engine.on("success", (event, almanac, ruleResult) => {
    almanac.factValue("studentName").then((studentName) => {
      switch (event.type) {
        case "physics-favorite-subject":
          console.log(
            studentName,
            "HAS".green,
            "Physics as their favorite subject"
          );
      }
    });
  });

  engine.on("failure", (event, almanac, ruleResult) => {
    almanac.factValue("studentName").then((studentName) => {
      switch (event.type) {
        case "physics-favorite-subject":
          const studiesMathResult = ruleResult.conditions.all.find(
            (condition) => condition.fact === "studiesMathematics"
          );
          if (studiesMathResult) {
            if (studiesMathResult.result) {
              console.log(
                studentName,
                "DOES NOT".red,
                "have Physics as favorite subject"
              );
            } else {
              console.log(
                studentName,
                "CANNOT NOT".red,
                "have Physics as favorite subject as they do not study Mathematics"
              );
            }
          }
      }
    });
  });

  Promise.all([
    engine.run({ studentName: "samuel" }),
    engine.run({ studentName: "joseph" }),
    engine.run({ studentName: "anthony" }),
  ]);

  // await engine.run({ studentName: "samuel" });
  // await engine.run({ studentName: "joseph" });
  // await engine.run({ studentName: "anthony" });
}

start();

student-api-client.js

"use strict";

require("colors");
const fs = require("fs");

let studentData = require("./student-data.json");

/**
 * mock api client for retrieving student information
 */
module.exports = {
  getStudentInformation: (studentName) => {
    const message = 'loading student information for "' + studentName + '"';
    console.log(message.dim);
    return new Promise((resolve, reject) => {
      setImmediate(() => {
        resolve(studentData[studentName]);
      });
    });
  },
};


student-data.json

{
  "john": {
    "favoriteSubject": "Mathematics",
    "subjects": ["Physics", "Mathematics"]
  },
  "anthony": {
    "favoriteSubject": "Physics",
    "subjects": ["Physics", "Mathematics"]
  },
  "george": {
    "favoriteSubject": "History",
    "subjects": ["History", "Mathematics"]
  },
  "samuel": {
    "favoriteSubject": "Physics",
    "subjects": ["Physics", "History", "Geography", "Chemistry"]
  },
  "joseph": {
    "favoriteSubject": "Economics",
    "subjects": ["Economics", "Mathematics", "History"]
  }
}

Output

Running sequentially
loading student information...
loading student information for "samuel"
samuel CANNOT NOT have Physics as favorite subject as they do not study Mathematics
loading student information...
loading student information for "joseph"
joseph DOES NOT have Physics as favorite subject
loading student information...
loading student information for "anthony"
anthony HAS Physics as their favorite subject
Running parallelly (Promise.all)
loading student information...
loading student information...
loading student information...
loading student information for "samuel"
loading student information for "joseph"
loading student information for "anthony"
samuel CANNOT NOT have Physics as favorite subject as they do not study Mathematics
Lenguaje dominante
JavaScript
Estrellas
3.1k
Forks
507
Métricas de merge de PR
Sin PR fusionados en 30 d

Guía de contribución

No hay ninguna guía de contribución indexada para este repositorio

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de CacheControl/json-rules-engine

Todos los issues de CacheControl/json-rules-engine

Issues similares

Más issues de JavaScript

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.