📜 ⬆️ ⬇️

We suspend the execution of the application if the connection to the network is lost.

Under the cut, a short note on how to suspend the execution of your application when the connection to the Internet is broken and continue - when it is restored.

Imagine that your hypothetical application must execute a queue of http requests. What each next depends on the result of the previous one.

async function main () { let url = ' ... ' while (url) { const resp = await fetch(url) const json = await resp.json() url = json.url } } 

But if in the middle of this process communication with the Internet disappears, then the queue will be interrupted. Let's fix it.

To begin with, we will write a function that will return a promise that will be solved at the moment when the client resumes the connection:

 function awaitOnline () { return new Promise(resolve => { // Если клиент уже online — немедленно возвращаем результат if (navigator.onLine) { resolve() return } // Регистрируем обработчик и решаем промис как только клиет будет online window.addEventListener( 'online', () => resolve(), {once: true} // Автоматически удаляем обработчик после первого события ) }) } 

Now add it to our main code.

 async function main () { let url = ' ... ' while (url) { await awaitOnline() // Выполнение приостановится в этом месте до момента возобновления сети const resp = await fetch(url) const json = await resp.json() url = json.url } } 

In this simple way, with each iteration, our algorithm will check the status of the network, and will pause if there is no connection. And it will automatically continue execution from the same place as soon as the connection is restored.

Of course, this is not a panacea. But such a small hack will make your application a little more fault tolerant.

Source: https://habr.com/ru/post/436426/