У меня есть фрагмент кода, упрощенная версия которого выглядит следующим образом:
let dataStorage1; //declare global vars for easier access later on
let dataStorage2;
let stopLight = true; //this variable is used to 'mark' an iteration as successful (= true) or
//failed (= false) and in need of a retry before continuing to the next
//iteration
let delay = 2000; //the standard time for a delay between api calls
async function tryFetch() {
try {
dataStorage1 = await api.fetch('data_type_1'); //fetch needed data trough api, which
//fills the global variable with an
//object
dataStorage2 = await api.fetch('data_type_2'); //do the same
stopLight = true; //change the value of stopLight to true, thus marking this iteration
//as successful
} catch (err) {
console.log(err);
stopLight = false;
}
}
async function fetchData() {
stopLight = true; //change the stopLight to default before execution
await tryFetch(); //fetch data and assign it to variables
//this section is needed for retrial of fetching after a 2s delay if the first attempt was
//unsuccessful, which is repeated until it's either successful or critical error occurred
while (stopLight == false) {
setTimeout(async () => await tryFetch(), delay);
}
}
(async function main() {
await fetchData(); //finally call the function
setTimeout(main, delay); //repeat the main function after 2s
})();
Как видите, самовыполняющиеся псевдорекурсивные main()
вызовы await fetchData()
, затем fetchData()
вызывает await tryFetch()
и, наконец, tryFetch()
вызывает await api.fetch('~')
, как это определено в API.
Однако, как только я запустил скрипт и приостановил его после пары итераций, я заметил, что оба dataStorage1
и dataStorage2
остаются undefined
. Если я go последовательно и последовательно выполняю код в отладчике, то происходит следующее: выполнение начинается в начале fetchData()
, перемещается в строку await tryFetch();
, пропускает ее и затем переходит к следующей итерации.
Для справки, если я вызываю dataStorage1/2 = await api.fetch(`~`);
в теле main()
напрямую, без вложенности, он работает отлично (если не возникает ошибка, поскольку они не обрабатываются должным образом).
Итак, мой вопрос, что я пропустил?