Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

140
Vistas
Return values from Remark rather than a promise

I have a JSON file wth a list of markdown values, I'm using Remark to parse them to HTML. After each value is parsed I add it to an object so it's accessible, however I think I'm getting stuck somewhere in promise land because the values in the object are undefined.

let sections = {};

const parseMD = (val) => {
    let parse = new Promise((resolve, reject) => {
        const file = 
            unified()
            .use(remarkParse)
            .use(remarkRehype)
            .use(rehypeStringify)
            .process(val.body);

        resolve(file);

    });

    parse.then(
        function (str) {
            sections[val.id] = str.value;
        }
    );

    return parse;
}

contents.forEach((val) => parseMD(val).then((val) => val).catch(err => console.log(err)));

As far as I can tell this should work... If I add a console.log(sections) I get {}, which looks like an empty object but when I expand it I see that all my content is in it:

section1: "blah blah blah",
section2: "something else"
...

But sections[section1] will be undefined.

This feels like I'm getting held up in the promise somewhere but I don't know how to fix it.

I've also tried this with async/await in the for loop: content.sections.forEach(async (val) => await parseMD(val)); same results.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

If I add a console.log(sections) I get {}

This is probably because you perform this output as part of the synchronous execution, and do not wait for the promise to resolve. In short, you should only print sections when you are within a then callback, as that will only execute when the object has been populated.

Not your problem, but you should not create a new Promise when you already have one -- it doesn't bring any additional value.

Also, it is bad practice to mutate a global variable (sections) inside a function. Instead, let your parseMD be more independent, and let it just resolve to the information you need for that input string (the id and the value), and leave it to the user of that promise to combine those pairs of information into an object sections.

So do like this:

const parseMD = (val) => unified()
    .use(remarkParse)
    .use(remarkRehype)
    .use(rehypeStringify)
    .process(val.body)
    .then(str => [val.id, str.value]); // No access to `sections` here! Just the pair

Promise.all(contents.map(parseMD)) // Wait for ALL those little promises to resolve
    .then(Object.fromEntries) // Collect the pairs into an object
    .then(sections => { // This is the accumulated object we need
        // Do all you wish to do with sections here (not in global scope)
        console.log(sections);
    })
    .catch(console.log);
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda