Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

330
Views
¿Cómo puedo implementar funciones asíncronas en mi código?

Tengo el siguiente código que se llama después de la función nativa player.loadNewVideoById de 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); }

Si no llamo a un tiempo de espera, la identificación del jugador no está definida y la función no está haciendo lo que se supone que debe hacer. ¿Cómo puedo convertir esto en una función asíncrona, para que se ejecute después de que el reproductor se haya inicializado?

Conozco la función OnReady de la API iframe de YouTube, pero no se llama cuando se actualiza el reproductor, solo si se creó.

¡Cualquier ayuda es apreciada!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

No tengo suficiente código de muestra para probar esta respuesta atm, pero debería verse así.

 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();

Tal vez un formato más fácil de leer es el try/catch. De cualquier manera, la clave es la declaración de async function y la palabra clave await donde se devolverá la promesa.

 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();

Muchos más ejemplos aquí: Cómo devolver la respuesta de una llamada asíncrona

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!