Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

116
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda