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

329
Vistas
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 Respuestas
Responde la pregunta

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 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