The JavaScript APIs based on Promises

The new asynchronous JavaScript APIs are now based on the Promise pattern instead of events and callbacks. And the new versions of the old JavaScript APIs are now based on Promises.

For example, the old version of the Battery status API and the Web Cryptography API were based on event, but the new versions of these APIs are purely implemented using Promises. Let's see an overview of these APIs.

The Battery Status API

The Battery Status API provides us the battery's current charge level and charging status. Here is a code example of the new Battery Status API:

navigator.getBattery().then(function(value){
  console.log("Batter Level: " + (value.level * 100));
}, function(reason){
  console.log("Error: " + reason);
});

The getBattery() method of the navigator object returns a fulfilled Promise if it has successfully retrieved the battery information. Otherwise, it returns a rejected Promise.

If the Promise is fulfilled, then the fulfillment value is an object holding the battery information. The level property of the fulfillment value represents the level of charge remaining.

The Web Cryptography API

The Web Cryptography API lets us do hashing, signature generation and verification, encryption and decryption.

Here is a code example of the new Web Cryptography API:

function convertStringToArrayBufferView(str)
{
    var bytes = new Uint8Array(str.length);
    for (var iii = 0; iii < str.length; iii++)
    {
        bytes[iii] = str.charCodeAt(iii);
    }

    return bytes;
}

function convertArrayBufferToHexaDecimal(buffer)
{
    var data_view = new DataView(buffer)
    var iii, len, hex = '', c;

    for(iii = 0, len = data_view.byteLength; iii < len; iii++)
    {
        c = data_view.getUint8(iii).toString(16);
        if(c.length < 2)
        {
            c = '0' + c;
        }

        hex += c;
    }

    return hex;
}


window.crypto.subtle.digest({name: "SHA-256"}, convertStringToArrayBufferView("ECMAScript 6")).then(function(result){
  var hash_value = convertArrayBufferToHexaDecimal(result);
  console.log(hash_value);
});

In this code example, we will find the SHA-256 hash value of a string.

The window.crypto.subtle.digest method takes an array buffer of a string and hash the algorithm name, and returns a Promise object. If it has successfully produced the hashes value, then it returns a fulfilled Promise and the fulfillment value is an array buffer representing the hash value.

The Web Cryptography API
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.17.168