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

323
Visualizações
How can I implement async functions in my code?

I have the following code which is being called after the native player.loadNewVideoById function from youtube.

function initSliderAndTime() {

    setTimeout(() => {
        var durationInSeconds = player.getDuration()
    
        $('#time-slider').attr('max', player.getDuration().toString().match(/^-?\d+(?:\.\d{0,1})?/)[0])
    
        $('#end-time')[0].innerText = calculateTimeFormat(durationInSeconds);
        
    }, 1000);

}

If I don't call a time out the player id is undefined and the function ins't doing what it it supposed to do. How can I turn this into an asynchronous function, so that it executes after the player has initialised.

I know about the OnReady Function from youtube's iframe api, but that doesn't get called when the player is updated, only if it created.

Any help is appreciated!

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I don't have enough sample code to test this answer atm but it should look something like this.

async function initSliderAndTime() {
    let myPromise = new Promise( function( resolve ) {
        resolve( player.getDuration() );
    });
    
    myPromise.then (
        let maxTime = await myPromise;
        
        $('#time-slider').attr('max', maxTime.toString().match(/^-?\d+(?:\.\d{0,1})?/)[0]);
        $('#end-time')[0].innerText = calculateTimeFormat(durationInSeconds);
    );
}

initSliderAndTime();

Maybe an easier more readable format is the try/catch. Either way the key is the async function declaration and the await keyword where the promise will be returned.

async function initSliderAndTime() {
    try {
        let durationInSeconds = await player.getDuration();
        $('#time-slider').attr('max', durationInSeconds.toString().match(/^-?\d+(?:\.\d{0,1})?/)[0]);
        $('#end-time')[0].innerText = calculateTimeFormat(durationInSeconds);
    } catch(error) {
        return null;
    }
}

initSliderAndTime();

Lots more examples here: How to return the response from an asynchronous call

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