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

277
Vistas
Is it OK to pass an async function to setImmediate in order to call an arbitrary function asynchronously?

I want to call a given function asynchronously. The wrapper function tryCallAsync is one way of doing this. This approach works. However, it requires that the callback for setImmediate to be an async function. This seems wrong, as the callback is returning a Promise that is not used. Is it wrong to pass an async function to setImmediate for this purpose?

async function tryCallAsync(fn, ...args) {

    return new Promise((r, j) => {

        setImmediate(async () => {

            try {
                r(await fn(...args));
            }
            catch (e) {
                j(e);
            }
        })
    })
}

//  Using tryCallAsync

let resolveAsync = tryCallAsync(()=>{
    return new Promise((r,j)=>{
        setImmediate(()=>r('resolveAsync'));
    });
})

resolveAsync.then((resolve)=>console.log(resolve));

let resolve = tryCallAsync(()=>{
    return 'resolve';
});

resolve.then((resolve)=>console.log(resolve));

NB: https://www.youtube.com/watch?v=e3Nh350b6S4

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

Yes, it's wrong, for multiple reasons:

  • setImmediate doesn't handle the returned promise, especially it doesn't deal with errors1
  • Don't put business logic in asynchronous (non-promise) callbacks when using promises. Settle a promise from there, nothing else.

1: And even while your particular callback never rejects the returned promise due to the try/catch, it still feels wrong

Your function should be written as

async function tryCallAsync(fn, ...args) {
    await new Promise(resolve => {
        setImmediate(resolve);
    });
    return fn(...args);
}
over 4 years ago · Santiago Trujillo Denunciar

0

This approach doesn't waste a Promise, however, still, it's not as performant as the conventional way of doing this.

function tryCallAsync(fn, ...args) {

    return new Promise((r, j) => {

        setImmediate(() => {

            (async function () {

                return await fn(...args);

            })().then(r).catch(j);
        });
    });
}
over 4 years ago · Santiago Trujillo 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