Explore our latest thought leadership, ideas, and insights on the issues that are shaping the future of business and society.
Choose a partner with intimate knowledge of your industry and first-hand experience of defining its future.
Discover our portfolio – constantly evolving to keep pace with the ever-changing needs of our clients.
Become part of a diverse collective of free-thinkers, entrepreneurs and experts – and help us to make a difference.
See our latest news, and stories from across the business, and explore our archives.
We are a global leader in partnering with companies to transform and manage their business by harnessing the power of technology.
Our number one ranked think-tank
Explore our brands
Explore our technology partners
Software applications often work synchronously in that they start a task and then must wait for it to finish before starting a new task. While that is the only choice for some types of processing, an alternative using asynchronous processing can be a better solution as it allows the application to perform multiple tasks simultaneously. In asynchronous algorithms, multiple tasks can be started but eventually, processing can only continue when all of them have completed. This speeds up application performance but does require coordination to ensure that all started tasks have completed before the application is allowed to continue with the processing of the results. Consider this Node.js application:
This example uses the fs-extra node module to look for a directory, create one if it doesn’t exist, empty that directory if there are any files in it, create a newfile.txt, and then read that file.
When running this code, the console should print:
Anyone who has encountered asynchronous code, though, will know that this is not the case. Here is an example of what is logged:
The code above is attempting to read the newfile.txt before the outputFile method has finished creating it.
In the following example, Promises are used to make sure each asynchronous step in creating the file is completed before the next one begins.
The code above produces this output:
To clean up the promise chain above, you can use the Async and Await keywords. A function declared with the ‘async’ keyword indicates that the function will be handling asynchronous operations. The declaration would look like this:
Here is our code using async and await:
Much cleaner! This implements exactly the same functions as the example above while using 30 fewer lines of code. In addition, readability and maintainability are enhanced by eliminating the nested chain of promises.
You may accept all cookies, or choose to manage them individually. You can change your settings at any time by clicking Cookie Settings available in the footer of every page.