Skip to content

J130 Asynchronous Programming

A task focusing on asynchronous programming in JavaScript using Promises.

Objective: Understand the nature of asynchronous code and learn to control the flow of execution using Promises or the async/await syntax.

Setup: Create an empty folder and within it, create a file named app.js. Copy the following function into the file:

const writeStar = ms =>
  new Promise(resolve => {
    console.log("Waiting " + ms + " ms to write the star...");
    setTimeout(() => {
      console.log("*");
      resolve();
    }, ms);
  });

The function, when called with a number of milliseconds (ms), starts by printing “Waiting [x] ms to write the star…”, and after [x] milliseconds, it prints a star in the console.

Now, add the following code after the function:

console.log("Start");
writeStar(2000);
console.log("End");
When you run this, you’ll notice the console displays:

Start
Waiting 2000 ms to write the star...
End
*

The star appears after “End”, which is not the desired behavior. The goal is to have the star appear before “End”. The problem arises because the function is asynchronous.

Your task is to adjust the function call to ensure the console output is:

Start
Waiting 2000 ms to write the star...
*
End

The method returns a Promise object which contains a then method. This method accepts a function that executes once the Promise object has been resolved. Try to rewrite the function call to use the then method. Alternatively, you can restructure the code using the await syntax. But remember that await needs to be inside an async function.

Solution

Here are two ways to achieve the desired output:

1. Using Promises with the then method:

console.log("Start");
writeStar(2000).then(() => {
    console.log("End");
});

2. Using the async/await syntax:

async function run() {
    console.log("Start");
    await writeStar(2000);
    console.log("End");
}

run();