xxxxxxxxxx
// some functions
function foo() {
console.log("foo")
}
function bar() {
console.log("bar")
}
/* due to the javascript event-loop behavior this code
is going to be asynchronous but what does that mean?
well, first you need to understand the concept of asynchronous,
In computer programming, asynchronous operation means that a
process operates independently of other processes.
*/
setTimeout(foo, 2000)
console.log("faz")
bar()
// this code above is going to print out:
// "faz"
// "bar"
// "foo"
/* this happens because the event loop first executes all the synchronous code
then waits for the timer to complete and then when it's done puts the callback
that we passed it in as a first param in something called the task queue where
it will be added to the call stack and executed
xxxxxxxxxx
// some functions
function foo() {
console.log("foo")
}
function bar() {
console.log("bar")
}
/* due to the javascript event-loop behavior this code
is going to be asynchronous but what does that mean?
well, first you need to understand the concept of asynchronous,
In computer programming, asynchronous operation means that a
process operates independently of other processes.
*/
setTimeout(foo, 2000)
console.log("faz")
bar()
// this code above is going to print out:
// "faz"
// "bar"
// "foo"
/* this happens because the event loop first executes all the synchronous code
then waits for the timer to complete and then when it's done puts the callback
that we passed it in as a first param in something called the task queue where
it will be added to the call stack and executed
xxxxxxxxxx
//Asynchronous JavaScript
console.log('I am first');
setTimeout(() => {
console.log('I am second')
}, 2000)
setTimeout(() => {
console.log('I am third')
}, 1000)
console.log('I am fourth')
//Expected output:
// I am first
// I am fourth
// I am third
// I am second
xxxxxxxxxx
//Asynchronous JavaScript
console.log('I am first');
setTimeout(() => {
console.log('I am second')
}, 2000)
setTimeout(() => {
console.log('I am third')
}, 1000)
console.log('I am fourth')
//Expected output:
// I am first
// I am fourth
// I am third
// I am second
In this example, the fetchData function is defined as an asynchronous function that returns a promise. The await keyword is used to pause the execution of the function until the promise is resolved, allowing the function to perform asynchronous operations without blocking the main thread.
When the fetchData function is called, it sends a request to a server using the fetch function and waits for the response. Once the response is received, the json method is used to parse the response and return it as JSON data.
The returned promise is then handled using the .then and .catch methods. If the promise is resolved successfully, the data is logged to the console. If an error occurs during the asynchronous operation, the error is caught and logged to the console.
xxxxxxxxxx
// Define an asynchronous function that returns a promise
async function fetchData() {
// Use the fetch() function to send a request to a server
const response = await fetch('https://example.com/data');
// Use the json() method to parse the response and return it as JSON
const data = await response.json();
// Return the data
return data;
}
// Call the asynchronous function and handle the returned promise
fetchData()
.then(data => {
// Do something with the data
console.log(data);
})
.catch(error => {
// Handle any errors that occur during the asynchronous operation
console.error(error);
});
Coded by Anshul Soni
https://anshulsoni.tech
xxxxxxxxxx
// Asynchronous function that returns a promise
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Data fetched successfully!');
}, 2000);
});
}
// Asynchronous function using async/await
async function processAsyncData() {
try {
console.log('Fetching data...');
const data = await fetchData(); // Waiting for the promise to resolve
console.log('Data received:', data);
console.log('Processing data...');
// Simulating additional asynchronous operation
await new Promise(resolve => setTimeout(resolve, 1000));
console.log('Data processed successfully!');
} catch (error) {
console.error('Error:', error);
}
}
// Call the asynchronous function
processAsyncData();
xxxxxxxxxx
console.log ('Starting');
let image;
fetch('coffee.jpg').then((response) => {
console.log('It worked :)')
return response.blob();
}).then((myBlob) => {
let objectURL = URL.createObjectURL(myBlob);
image = document.createElement('img');
image.src = objectURL;
document.body.appendChild(image);
}).catch((error) => {
console.log('There has been a problem with your fetch operation: ' + error.message);
});
console.log ('All done!');
xxxxxxxxxx
<script>
document.write("Hi");
document.write("<br>");
setTimeout(() => {
document.write("Let us see what happens");
}, 2000);
document.write("<br>");
document.write("End");
document.write("<br>");
</script>
/*Hi
End
Let us see what happens*/