Files
nahodka-front/src/utils/ymapsApi.js
2026-10-06 01:24:28 +03:00

33 lines
1.3 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* public/index.html подключает API Яндекс.Карт через <script defer>,
* поэтому к моменту первого рендера window.ymaps может быть ещё undefined:
* скрипт не скачался, медленный CDN, блокировщик рекламы, офлайн.
*
* Без ожидания карта просто не создаётся — пользователь видит вечный спиннер
* без единой ошибки. Поэтому ждём появления API, но с таймаутом, и отдаём
* вызывающему явную ошибку вместо бесконечной загрузки.
*/
const DEFAULT_TIMEOUT_MS = 10000;
const POLL_INTERVAL_MS = 100;
export function whenYmapsReady(timeoutMs = DEFAULT_TIMEOUT_MS) {
if (window.ymaps?.ready) return Promise.resolve(window.ymaps);
return new Promise((resolve, reject) => {
const startedAt = Date.now();
const timer = setInterval(() => {
if (window.ymaps?.ready) {
clearInterval(timer);
resolve(window.ymaps);
return;
}
if (Date.now() - startedAt >= timeoutMs) {
clearInterval(timer);
reject(new Error("YMAPS_LOAD_FAILED"));
}
}, POLL_INTERVAL_MS);
});
}