Concepts: Using JavaScript Promises

In this topic, you will learn how to use JavaScript Promises, which are returned by some Brightcove Player methods.

Simple Promise

Although it is NOT the purpose of this document to teach you how to write a JavaScript Promise, to understand how to use them it is instructive to see how a simple Promise is coded.

In the following, a Promise is created that returns a string that states whether a task was completed or not. The key point is that either the Promise.resolve() or Promise.reject() method is called. In this case a simple string is passed by both methods, but this could be an object.

let promiseToFinishTask = new Promise(function(resolve, reject) {        
  //Business logic to set taskComplete boolean
  let taskComplete = true;
  if (taskComplete) {
    resolve('Yea, I am done');
  } else {
    reject('Not quite done');

Now you will see how to deal with the returned Promise information, which is what you will do with some Brightcove Player API method calls. The basic handling of a follows:

  // Function call for promise resolved
  // Function call for promise rejected

Handling the simple example above would appear as shown here:

promiseToFinishTask.then(function(fromResolve) {
}).catch(function(fromReject) {

If the Promise is resolved the then code is executed, and if the Promise is rejected the catch code is executed. For the example, one of the strings Yea, I am done or Not quite done would appear based on the business logic that set the taskComplete variable's value.

Brightcove example

The Brightcove Player's play() method may return a Promise that can be used to check if the player could autoplay the video currently in the player. The code that deals with the Promise is highlighted:

var myPlayer = videojs.getPlayer('myPlayerID');
myPlayer.on('loadedmetadata',function() {
  var promise =;
  if (promise !== undefined) {
    promise.then(function() {
      // Autoplay started!
    }).catch(function(error) {
      // Autoplay was prevented.

Based on this you can then code behaviors if the video autoplayed or not. For a specific use case playing the video, with audio when possible, see the Specific use case section of the Autoplay Considerations document.

For complete information on JavaScript Promises see the MDN Promise document.

Promise versus callback

In this section the Catalog's get() method is used to demonstrate the syntax difference between using a Promise versus a callback function. The get() method can be used with either approach.

Promise syntax

The following is a snippet of code showing the call to the get() method, handling the response as a Promise:


Callback function syntax

The following is a snippet of code showing the call to the get() method, handling the response with a callback function: