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?
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" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With