Please tell me how to make the function getGameSound return the result of the method thisAudio.onloadedmetadata in getGameSound duration. The result of the method should be the duration of setTimeout.

TheGunman.prototype.getGameSounds = function (action) { var audioTmpl = '<audio id=":action" src=":path:action:expansionSound" autoplay></audio>'; var getAudio = audioTmpl.replace(/:action/gi, action).replace(/:path/gi, this.pathSound).replace(/:expansionSound/gi, this.expansionSound); this.GameObject.frame.append(getAudio); var thisAudio = document.querySelector('#' + action); // результат выполнения этого метода надо вернуть в функцию из которой вызывался getGameSound return thisAudio.onloadedmetadata = function () { return thisAudio.duration * 1000; } }; TheGunman.prototype.startGame = function () { var __self = this; var duration = // длительность звука вернувшего из функции getGameSounds this.getGameSounds('intro'); setTimeout(function () { __self.CreateNewEnemy(); }, duration); 
  • If the result is not immediately known, then via callback / promise, as usual. - Vladimir Gamalyan

1 answer 1

Use Promise , as long as it is a good solution (better async/await , but this is only promised in ES2017 ).

 function start(){ getTime().then(duration => { // Получаем значение времени после разрешения обещания (после вызова в нём resolve) // Через 4s исполняем код таймера (в данном случае, выводим надпись) setTimeout(() => console.info("Let's rock!"), duration); }); } function getTime(){ // Делаем что-то несомненно важное, если нужно... // Ожидание асинхронного кода (неизвестно когда произойдёт); решаем по современному: Promise return new Promise((resolve, reject) => { // Эмулируем ожидание через таймер на 1 секунду, ожидание может быть чего угодно setTimeout(resolve(3000), 1000); // 3s будут как возвращённое время }); } start();