Complete Communications Engineering

Internet applications, such as those that use WebRTC, are often implemented in JavaScript when browser support is required.  Modern JavaScript has a number of features that support running background processes and synchronizing those processes so they run in the proper order.  For example, a WebRTC application may require the use of audio equipment.  When the JavaScript makes this request, the web browser may prompt the user for permission.  The JavaScript running on the web page will need to wait for this permission before setting up the connection.

JavaScript applications can use the async and await keywords to start and synchronize background processes.  The async keyword builds on JavaScript promise objects.  It doesn’t introduce any new functionality, but it does make the code more understandable.  A promise object represents a task that will be resolved later.  When an async function is invoked, it automatically runs in parallel with the calling code.  Because of this, async functions are suitable to be called from the GUI, for example on button presses, even if their execution takes a long time.  Inside the async function, the await keyword can be used to wait for promise objects to resolve.  This can be used with function calls that return promise objects, and it will cause the background task to wait for the promise to resolve before proceeding.

The following code example illustrates using async and await in JavaScript:

// Function returning a promise which can be waited on

function sleep(ms) {

   

    // resolve is called after the given timeout

    return new Promise(resolve => setTimeout(resolve, ms));

}

 

// Asynchronous function call, will run in parallel with the code that invokes it

async function asyncCall() {

   

    // Wait for first task to complete

    console.log(‘first’);

    await sleep(1000);

 

    // Wait for second task to complete

    console.log(‘second’);

    await sleep(1000);

   

    console.log(‘done.’);

}

 

asyncCall();