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

110
Vistas
JavaScript How to execute firstPromise before secondPromise

This might seem a silly question, but I am a newbie in this topic. In the script below i have two promises. By now "secondPromise" executing first, and then executing "firstPromise". Cuz in the "secondPromise" i set less time. But how to execute "firstPromise" first, after finished that, start executing the "secondPromise"? How to rewrite the script below

(async function()
{
//var final = new Array();
var final;
const firstPromise = new Promise(
function(resolve)
{
    let result = 2 + 2;
    resolve(result);
    setTimeout(() => console.log("please show me first"), 2000);
});
const secondPromise = new Promise(
function(resolve)
{
    let result2 = 0;
    resolve(result2 + 1);
    setTimeout(() => console.log("please show me second"), 1000);
});
var myP = Promise.all([firstPromise, secondPromise]).then((values) => {
    return values[0]+values[1];
  });
return myP;
})();

(async function()
{
//var final = new Array();
var final;
const firstPromise = new Promise(
function(resolve)
{
    let result = 2 + 2;
    resolve(result);
    setTimeout(() => console.log("please show me first"), 2000);
});

const secondPromise = new Promise(
function(resolve)
{
    let result2 = 0;
    resolve(result2 + 1);
    setTimeout(() => console.log("please show me second"), 1000);
});

var myP = Promise.all([firstPromise, secondPromise]).then((values) => {
    return values[0]+values[1];
  });
return myP;
})();

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

0

Quentin's answer is correct: the function you pass to new Promise happens immediately. However: because you already have this in an async function, you can await Promises within it. This pauses the async function until the Promise resolves, so unlike your function with Promise.all that waits for your explicit new Promise Promises in parallel, my function waits for those Promises serially.

Furthermore, if you want the new Promise constructions you wrote to wait for the action in setTimeout, you need to wait and call the resolve method within the callback that setTimeout calls, not outside them as you have it.

console.log("start");
(async function () {
    const firstValue = await new Promise(
        //             ^^^^^
        function (resolve) {
            let result = 2 + 2;
            setTimeout(() => {
                console.log("please show me first");
                resolve(result);  // Promise resolves after 2000ms
            }, 2000);
        });

    const secondValue = await new Promise(
        //              ^^^^^
        function (resolve) {
            let result2 = 0;
            setTimeout(() => {
                console.log("please show me second");
                resolve(result2 + 1);
            }, 1000);
        });
    // These are values, not promises, because you await them.
    // However, the async function still returns a Promise, because
    // "async" covers the asynchronicity of the Promises you await.
    return firstValue + secondValue;
})().then(x => console.log(x));  // or .then(console.log)

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can't execute a promise.

You can execute a function.

If you pass a function to a Promise constructor, then it will be executed (by the Promise constructor) immediately.

There is no way to delay the execution of a function passed to a Promise constructor.

You could wrap your calls to new Promise in functions, and then only call the second function when the first promise is resolved.

(Note, however, that in your examples the calls to setTimeout happen after the resolve function is called).

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