Using Async/Await with Dynamic imports in JavaScript
Async/Await with Dynamic Imports:
Write a JavaScript program that dynamically imports a module and uses an async function from that module.
Solution:
Code:
// --- file: mathOperations.js ---
// Export an async function for demonstration
export async function fetchData() {
// Simulate a delay with a Promise
return new Promise((resolve) => {
setTimeout(() => resolve('Data fetched successfully!'), 1000);
});
}
// --- file: app.js ---
// Dynamically import the module and use the async function
async function loadAndExecute() {
// Dynamically import the module
const module = await import('./mathOperations.js');
// Call the async function from the module
const result = await module.fetchData();
console.log(result); // Output: Data fetched successfully!
}
Output:
Data fetched successfully!
Explanation:
- 'mathOperations.js' exports an async function 'fetchData' that simulates a delay and returns a message.
- 'app.js' dynamically imports the 'mathOperations' module using 'import()'.
- The 'loadAndExecute' function calls the async 'fetchData' and logs the resolved value.
Code:
// --- file: main.js ---
// Dynamically import the module and use the async function
async function processString(input) {
// Dynamically import the module
const module = await import('./stringUtilities.js');
// Call the async function from the module
const reversed = await module.reverseString(input);
console.log(reversed); // Output: reversed string of input
}
processString('hello');
// --- file: stringUtilities.js ---
// Export an async function for string manipulation
export async function reverseString(str) {
// Simulate a delay with a Promise
return new Promise((resolve) => {
setTimeout(() => resolve(str.split('').reverse().join('')), 1000);
});
}
Output:
olleh
Explanation:
- 'stringUtilities.js' exports an async function 'reverseString' that reverses a string after a simulated delay.
- 'main.js' dynamically imports the 'stringUtilities' module using 'import()'.
- The 'processString' function calls the async 'reverseString' and logs the result, demonstrating dynamic.
Improve this sample solution and post your code through Disqus
Previous: Create Debounced Functions in JavaScript with Promises.
Next: Promise.race in JavaScript with Practical Examples.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics