w3resource

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.

For more Practice: Solve these Related Problems:

  • Write a JavaScript function that dynamically imports a module and invokes an async function from that module to process data.
  • Write a JavaScript function that conditionally loads a module using dynamic import and async/await based on user input.
  • Write a JavaScript function that handles errors gracefully when dynamically importing a module using async/await.
  • Write a JavaScript function that uses dynamic imports with async/await to lazy load a utility module on demand.

Go to:


PREV : Creating a Debounce Function.
NEXT : Promise.race Exercise.

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.