Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the right way for handling Async functions for loading a .gif image?

For example, look at this code:

function myPromise() {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve('Stack Overflow');
        }, 2000);
    });
}
async function sayHello() {
     const externalFetchedText = await myPromise();
     console.log('Hello ' + externalFetchedText);
}

sayHello();

What's the right way for showing a (.gif image file) loading before the request and hide this after Promise is resolved and the process is finished?

like image 877
Mohammad Avatar asked Jan 20 '26 15:01

Mohammad


1 Answers

Most of time promises are abstracted into seprated module and are independent. So you should never do any other operation than async operation in the promises. You can show your gif while resolving the promises. See below code to show animation after you make async call, and hide it after resolution. You also have to handle reject scenario via try/catch/finally block.

function myPromise() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve('Stack Overflow');
            // reject('Some Error')
        }, 2000);
    });
}

function showSpinner() {
  document.getElementById('loader').style.display = 'block';
}

function hideSpinner() {
  document.getElementById('loader').style.display = 'none';
}

async function sayHello() {
     try {
       showSpinner()
       const externalFetchedText = await myPromise();
       console.log('Hello ' + externalFetchedText);
     } catch (err) {
       console.error(err);
     } finally {
       hideSpinner()
     }
}

sayHello();
<img id="loader" style="display:none" src="http://chimplyimage.appspot.com/images/samples/classic-spinner/animatedCircle.gif" />
like image 164
Vipin Kumar Avatar answered Jan 23 '26 04:01

Vipin Kumar