Asynchronous Methods

Both the frontend and backend components provide methods that return a deferred promise.

For example, the setOption(cart_option_id, value) method of the ProductDetailsComponent (PDP) lets you set options for the currently displayed product. It returns a type of Deferred.<Boolean> that represents the eventual result of the set option operation, which is either true or false.

The following example show the usage of the setOption(cart_option_id, value) method. You can direct the extension to set the option and then check the value of the result after the promise returned by the method resolves:

          pdp.setOption(optionId, newValue)
.then(
  function(result) { 
    // check if result is false or true
  }
, function(error){
    console.log(error);
  }
); 

        
Note:

You can also implement similar functionality to make a call to an external, third-party validator to check the returned value and take different actions depending on the returned value.

You can also return a single promise for multiple method calls, where the promise does not resolve until both methods return a value.

In the following example, you call container.getComponent('Cart'), which gives you all methods associated with the Cart component. You then call both the cart.getLines() and cart.getPromotions() methods of CartComponent. Because this is asynchronous, the returned promise does not resolve until both methods complete and return a value:

          var cart = container.getComponent('Cart'); 

// ...

jQuery.when([cart.getLines(), cart.getPromotions()])
.then(function (result)
{
  var lines = result[0]
, promotions = result[1];
})
.catch(function(error)
{
  console.log(error);
}); 

        

The following example shows the above functionality for the cart.getLines() and cart.getPromotions() methods of CartComponent using a promise:

          var cart = container.getComponent('Cart'); 

// ...

Promise.all([cart.getLines(), cart.getPromotions()])
.then(function (result)
{
  var lines = result[0]
, ship_methods = result[1];
})
.catch(function(error)
{
  console.log(error);
}); 

        

Related Topics

Implement Asynchronous and Synchronous Methods
Backend Asynchronous and Synchronous Methods

General Notices