var Api = Class.create({ initialize: function(url) { this.url = url; }, call: function(method, params) { var requestBody = $H({ 'method' : method, 'params' : params }).toJSON(); var d = new Deferred(); var onSuccess = function(transport) { result = transport.responseText.evalJSON(); if ('faultCode' in result && 'faultString' in result) { var err = new Error(result.faultString); err.faultCode = result.faultCode; err.faultString = result.faultString; d.errback(err); } else { result = result[0]; console.log("Got result: ", result); d.callback(result); } }; var onFailure = function(transport) { d.errback(new Error("API transport error: " + transport.status)) }; var onException = function(error) { d.errback(error); } new Ajax.Request(this.url, { method: 'post', postBody: requestBody, requestHeaders: { 'Content-Type' : 'application/json' }, onSuccess: onSuccess, onFailure: onFailure, onException: onException, }); return d; }, });
Api.call
will return a new Deferred, which will contain the result of a remote call or an exception (transport or from the server we are accessing). Let there be RPC calls sum
and mult
, which, respectively, add and multiply their arguments. Then the calculation of the expression (2+3)*7
using our Api
class will look like this: var api = new Api; api.call('sum', [2, 3]) .addCallback( function (sum_of_2_and_3) { return api.call('mult', [sum_of_2_and_3, 7]); }) .addCallback( function(result) { alert('(2+3)*7 = ' + result); }) .addErrback( function (error) { alert('Mmm… something wrong happened: ' + error); });
Source: https://habr.com/ru/post/60956/
All Articles