Best practices for implementing asynchronous javascript programming with promise Q library - javascript

Already had a layer in JS which helps Gets and Posts to the server with the following implementations :
var getJson = function(url, callback, onError) {
$.get(url)
.done(function(data) {
if(callback != null)
callback(data);
})
.fail (function(error) {
if(onError != null)
onError (error);
else
my.notification.notifyError(onErrorMessage);
});
};
var postJSON = function(url, data, callback, onError) {
$.ajax({
url : url ,
type: "POST" ,
contentType : "application/json"
dataType : "json" ,
date : ko.toJSON(data)
})
.done(function(data) {
if(callback ! = null)
callback(data);
})
.fail(function(error) {
if(onError ! = null)
onError (error);
else
my.notification.notifyError(onErrorMessage);
});
};
Using these implementations on DataService layer :
// Get
var find = function(date, onSuccess , onError) {
var url = /* url with the Controller and Action */ + "?queryString = " + data.filter;
getJson(url , onSuccess , onError);
};
// Post
var save = function(date, onSuccess , onError) {
var url = /* url with the Controller and Action */;
postJSON(url, data, onSuccess, onError);
};
However we use webapi, wich in some cases, a request depends the result of another request generating a "Pyramid of Doom ".
For more elegance of code we are implementing the library Q for asynchronous programming.
To follow the pattern shown above using Q promisses was implemented new method of get as show:
var getJsonDefer = function(url, callback, onError) {
return Q.when($.getJSON(url))
.then (function(data) {
if(callback ! = null)
callback(data);
})
.fail (function(error) {
if(onError ! = null)
onError (error);
else
my.notification.notifyError(onErrorMessage);
});
};
I'm trying to use this implementation on DataService layer this way:
// Get
var find = function(date, onSuccess , onError) {
var url = /* url with the Controller and Action */ + "?queryString = " + data.filter;
return getJsonDefer(url, onSuccess, onError);
};
Anyway in my layer viewmodel javascript suppose I need to use 3 finds and one depends on the outcome of the other:
var = dataOne {
filter: " Filter"
};
findOne(dataOne,
function(result) {
return result;
}
function(error) {
throw error;
})
.then(function(args) {
var = datatwo {
filter: args
};
// Second
findTwo(datatwo ,
function(result) {
return result;
}
function(error) {
throw error;
}
);
})
.then(function(args) {
var = dataThree {
filter: args
};
// Third
findThree(dataThree,
function(result) {
return result;
}
function(error) {
throw error;
}
);
}).catch(function(error) {
// Handle any error from all above steps
})
.done();
My problem :
I admit that I am not able to implement the right way, because all my functions inside .then() are coming with undefined args.
I wonder know what is the best practice to meet the scenario propose here.

I think you will find that the appeal of promises is that you can accomplish your goals with much less code that before. There are a few things you’ll need to know about, though. For one, you will not need to pass or receive callbacks and errbacks anymore. You just need to make sure to return results or promises for results in your handlers. That is how the values propagate to the next handler.
This is an untested adaptation of your program that should illustrate the form:
var find = function(data) {
var url = /* url with the Controller and Action */ + "?queryString = " + data.filter;
return Q($.getJson(url));
};
find({filter: "filter"})
.then(function (firstResult) {
return find({filter: firstResult})
.then(function (secondResult) {
return find({filter: secondResult})
.then(function (thirdResult) {
return [firstResult, secondResult, thirdResult];
});
});
})
.fail(notifyError)
.done();
Note that an error in any stage will be handled by the single fail call at the bottom. Regardless of whether you have an error handler at the end, always end a chain with done() so that any errors that happen before, even in your fail handler, show up in your console.
Note that you only need to nest promises if one operation depends on the previous and the handler needs access both the first and second result. If you only need the result of the second operation, you can just chain.
find({filter: "filter"})
.then(function (firstResult) {
return find({filter: firstResult})
})
.then(function (secondResult) {
return find({filter: secondResult})
.then(function (thirdResult) {
return [secondResult, thirdResult];
});
});
.fail(notifyError)
.done();
You can also flatten things with Q.all and promise.spread, but I will leave you to the documentation at this point because, I hope, you get the gist.

Related

2 $http get function

Given 2 JSON url, how do I make sure the code has finished retrieving the data from a.json, then only start retrieving the data from b.json, then only run init function?
var aUrl = "a.json";
var bUrl = "b.json";
My attempt:
var app = angular.module('calendarApp', []);
app.controller('ctrl', function($scope, $http) {
$http.get(aUrl).success(function(data) { });
$http.get(bUrl).success(function(data) {
init()}
);
var init = function(){}
I faced the same issue in my initial days.
There are many ways of doing it exactly as suggested here.
You need to know below two things before exploring:
1. JavaScript is synchronous
Synchronous Example[Flow in sequence]:
console.log('1')
console.log('2')
console.log('3')
It logs 1 2 3.
Example of making service calls
1. $http.get(aUrl).success(function(data) { console.log('1.any time response returns') });
2. $http.get(bUrl).success(function(data) { console.log('2.mummy returns')};
So as single-threaded javascript will first make a call to your below code with $http.get(aUrl) which hits the url and processes to fetch the data from the background.
$http.get(aUrl).success(function(data) { console.log('1.any time response returns') });
But the key thing to notice here is $http.get(aUrl) requested above doesn't wait until the data is returned in success/error. It moves to the next request $http.get(bUrl) and we just can't predict which response comes earlier.
$http.get(bUrl).success(function(data) { console.log('2.mummy returns') }
Output might be either
1.any time response returns
2.mummy returns
or
2.mummy returns
1.any time response returns
So, to overcome this situation we follow asynchronous operations in various ways.
2. Asynchronous Calls
$http.get(aUrl)
.then(function(response){
console.log('inside the first then response');
console.log(response.data);
//executing the second request after we get the first request
//and returns the **outputResponse** which is captured in the next **then** block
return $http.get(bUrl);
})
.then(function(**outputResponse** ){
console.log('outputResponse generated from to the second bUrl');
//you can call init() here
});
Above code suffices your requirement.
Click for more info using $q in future
Click here to know why to use then instead of success.
Might not be the best or cleanest method but quickly making your code do what you want it to do I got:
var app = angular.module('calendarApp', []);
app.controller('ctrl', function($scope, $http) {
$http.get(aUrl).success(function(data) {
$http.get(bUrl).success(function(data) {
init()
}
});
);
var init = function(){}
You could create a service layer in which define the two methods. Then inject the service into your controller:
//Controller
YourService.getUrl(urlA).then(function(response) {
if(response != null && response.success == true){
// do something
}
YourService.getUrl(urlB).then(function(response) {
if(response != null && response.success == true){
// do something
init()
}
},
function errorCallback(response) {
console.log("Error YourService: getUrlB ---> ");
});
},
function errorCallback(response) {
console.log("Error YourService: getUrlA ---> ");
});
// Example of method in your service
this.getUrl = function(urlA) {
try{
var deferred = $q.defer();
$http({
method: 'GET',
url: getUrlA,
params: {},
responseType: "json",
cache: false
})
.success(function(data, status, headers, config) {
deferred.resolve(data);
})
.error(function(data, status, headers, config) {
deferred.reject(data);
});
return deferred.promise;
}catch(e){
/* */
console.log("Service: getUrl ---> " + e);
}
}
$http.get returns a promise, so you can do:
return $http.get(aUrl)
.then(function(result) {
return $http.get(bUrl);
})
.then(function(result) {
return init();
},
function (error) {
// do something with the error
});
I suggest to use AngularJS promises. Mainly it has the benefit of loading the data asynchronly at the same time without having to wait until the first request is finished. see: https://docs.angularjs.org/api/ng/service/$q
var promises = [];
var loadingJson = function(url){
var defer = $q.defer();
$http.get(url).then(function(results){
defer.resolve(results);
}, function(err){
defer.reject(err);
});
return defer.promise;
};
promise.push(loadingJson('example.com/1.json'));
promise.push(loadingJson('example.com/2.json'));
$q.all(promises).then(function(resultList){
// Your hanadling here, resultList contains the results of both API calls.
}, function(errList){
// Your error handling here.
});

JavaScript Promises

Im trying to understand promises, but Im hitting a roadblock, I'm trying to query my Parse database for the last ran date object so that ill know when it was ran last. Then pass that date to the next function who can check my movie database for anything after the last time it was called. (I'm doing this to send out push notifications for new fields manually entered into Parse class) then actually send the push. But I'm not understanding the .then and promises, I'm new to JavaScript so any help would be appreciated!
Here is my code i have now.
Parse.Cloud.job("TestSendNewMoviePush", function(request, response) {
var query = new Parse.Query("MovieStatus");
var lastRunDateQuery = new Parse.Query("LastRun");
var lastRunDate;
var newDate;
var newCount = 0;
var installQuery = new Parse.Query(Parse.Installation);
query.greaterThan("updatedAt", lastRunDate);
query.equalTo("CurrentStatus", "Ready");
query.equalTo("imageStatusName", "Green");
installQuery.equalTo("role", "downloader");
lastRunDateQuery.get("d3WeNEwzIu", {
success: function(lastDateRanObj) {
console.log("Got the object " + lastDateRanObj);
var date = new lastDateRanObj.updatedAt;
lastRunDate = lastDateRanObj.updatedAt;
console.log(lastRunDate);
return lastRunDate;
},
error: function(lastDateRanObj, error) {
console.log("Failed to get object");
}
}).then(
query.count({
success: function(count) {
newCount = count;
return newCount
},
error: function(e) {
}
})).then(
Parse.Push.send({
where: installQuery,
data: {
"alert": newCount + " new movie(s) available!",
"badge": "Increment"
}
}, {
success: function() {
response.success("Success");
},
error: function(e) {
response.error("Error:" + e.code);
}
}));
});
lastRunDateQuery.get() returns a Promise object, which you can chain with a then, which itself is a function taking 2 functions as arguments: one that is called if the promise is resolved, and one that is called if the promise is rejected. You use these instead of the success and error parameters:
lastRunDateQuery.get()
.then(function(data) {
// success!!
}, function(error) {
// error :(
});
The functions you passed as arguments to then can themselves return promises, which you may subsequently chain with a then. In the example below I have omitted the error callbacks:
lastRunDateQuery.get()
.then(function(data) {
// data is the result of lastRunDateQuery.get()
return query.count();
})
.then(function(data) {
// data is the result of query.count()
return someOtherThing.someOtherMethodReturningAPromise();
});
.then(function(data) {
// data is the result of someOtherThing.someOtherMethodReturningAPromise()
});
And so on.
I would recommend having a look at the Promises/A+ spec - it's very instructive.
EDIT:
If the chaining concept is a bit confusing just think of it as a shorthand for the following:
var aPromise = lastRunDateQuery.get();
aPromise.then(
function() {}, // promise was resolved -> call this function
function() {}, // promise was rejected -> call this function
);

Multiple Promise Chains in Single Function

I have some code that will dynamically generate an AJAX request based off a scenario that I'm retrieving via an AJAX request to a server.
The idea is that:
A server provides a "Scenario" for me to generate an AJAX Request.
I generate an AJAX Request based off the Scenario.
I then repeat this process, over and over in a Loop.
I'm doing this with promises here: http://jsfiddle.net/3Lddzp9j/11/
However, I'm trying to edit the code above so I can handle an array of scenarios from the initial AJAX request.
IE:
{
"base": {
"frequency": "5000"
},
"endpoints": [
{
"method": "GET",
"type": "JSON",
"endPoint": "https://api.github.com/users/alvarengarichard",
"queryParams": {
"objectives": "objective1, objective2, objective3"
}
},
{
"method": "GET",
"type": "JSON",
"endPoint": "https://api.github.com/users/dkang",
"queryParams": {
"objectives": "objective1, objective2, objective3"
}
}
]
This seems like it would be straight forward, but the issue seems to be in the "waitForTimeout" function.
I'm unable to figure out how to run multiple promise chains. I have an array of promises in the "deferred" variable, but the chain only continues on the first one--despite being in a for loop.
Could anyone provide insight as to why this is? You can see where this is occuring here: http://jsfiddle.net/3Lddzp9j/10/
The main problems are that :
waitForTimeout isn't passing on all the instructions
even if waitForTimeout was fixed, then callApi isn't written to perform multiple ajax calls.
There's a number of other issues with the code.
you really need some data checking (and associated error handling) to ensure that expected components exist in the data.
mapToInstruction is an unnecessary step - you can map straight from data to ajax options - no need for an intermediate data transform.
waitForTimeout can be greatly simplified to a single promise, resolved by a single timeout.
synchronous functions in a promise chain don't need to return a promise - they can return a result or undefined.
Sticking with jQuery all through, you should end up with something like this :
var App = (function ($) {
// Gets the scenario from the API
// sugar for $.ajax with GET as method - NOTE: this returns a promise
var getScenario = function () {
console.log('Getting scenario ...');
return $.get('http://demo3858327.mockable.io/scenario2');
};
var checkData = function (data) {
if(!data.endpoints || !data.endpoints.length) {
return $.Deferred().reject('no endpoints').promise();
}
data.base = data.base || {};
data.base.frequency = data.base.frequency || 1000;//default value
};
var waitForTimeout = function(data) {
return $.Deferred(function(dfrd) {
setTimeout(function() {
dfrd.resolve(data.endpoints);
}, data.base.frequency);
}).promise();
};
var callApi = function(endpoints) {
console.log('Calling API with given instructions ...');
return $.when.apply(null, endpoints.map(ep) {
return $.ajax({
type: ep.method,
dataType: ep.type,
url: ep.endpoint
}).then(null, function(jqXHR, textStatus, errorThrown) {
return textStatus;
});
}).then(function() {
//convert arguments to an array of results
return $.map(arguments, function(arg) {
return arg[0];
});
});
};
var handleResults = function(results) {
// results is an array of data values/objects returned by the ajax calls.
console.log("Handling data ...");
...
};
// The 'run' method
var run = function() {
getScenario()
.then(checkData)
.then(waitForTimeout)
.then(callApi)
.then(handleResults)
.then(null, function(reason) {
console.error(reason);
})
.then(run);
};
return {
run : run
}
})(jQuery);
App.run();
This will stop on error but could be easily adapted to continue.
I'll try to answer your question using KrisKowal's q since I'm not very proficient with the promises generated by jQuery.
First of all I'm not sure whether you want to solve the array of promises in series or in parallel, in the solution proposed I resolved all of them in parallel :), to solve them in series I'd use Q's reduce
function getScenario() { ... }
function ajaxRequest(instruction) { ... }
function createPromisifiedInstruction(instruction) {
// delay with frequency, not sure why you want to do this :(
return Q.delay(instruction.frequency)
.then(function () {
return this.ajaxRequest(instruction);
});
}
function run() {
getScenario()
.then(function (data) {
var promises = [];
var instruction;
var i;
for (i = 0; i < data.endpoints.length; i += 1) {
instruction = {
method: data.endpoints[i].method,
type: data.endpoints[i].type,
endpoint: data.endpoints[i].endPoint,
frequency: data.base.frequency
};
promises.push(createPromisifiedInstruction(instruction));
}
// alternative Q.allSettled if all the promises don't need to
// be fulfilled (some of them might be rejected)
return Q.all(promises);
})
.then(function (instructionsResults) {
// instructions results is an array with the result of each
// promisified instruction
})
.then(run)
.done();
}
run();
Ok let me explain the solution above:
first of all assume that getScenario gets you the initial json you start with (actually returns a promise which is resolved with the json)
create the structure of each instruction
promisify each instruction, so that each one is actually a promise whose
resolution value will be the promise returned by ajaxRequest
ajaxRequest returns a promise whose resolution value is the result of the request, which also means that createPromisifiedInstruction resolution value will be the resolution value of ajaxRequest
Return a single promise with Q.all, what it actually does is fulfill itself when all the promises it was built with are resolved :), if one of them fails and you actually need to resolve the promise anyways use Q.allSettled
Do whatever you want with the resolution value of all the previous promises, note that instructionResults is an array holding the resolution value of each promise in the order they were declared
Reference: KrisKowal's Q
Try utilizing deferred.notify within setTimeout and Number(settings.frequency) * (1 + key) as setTimeout duration; msg at deferred.notify logged to console at deferred.progress callback , third function argument within .then following timeout
var App = (function ($) {
var getScenario = function () {
console.log("Getting scenario ...");
return $.get("http://demo3858327.mockable.io/scenario2");
};
var mapToInstruction = function (data) {
var res = $.map(data.endpoints, function(settings, key) {
return {
method:settings.method,
type:settings.type,
endpoint:settings.endPoint,
frequency:data.base.frequency
}
});
console.log("Instructions recieved:", res);
return res
};
var waitForTimeout = function(instruction) {
var res = $.when.apply(instruction,
$.map(instruction, function(settings, key) {
return new $.Deferred(function(dfd) {
setTimeout(function() {
dfd.notify("Waiting for "
+ settings.frequency
+ " ms")
.resolve(settings);
}, Number(settings.frequency) * (1 + key));
}).promise()
})
)
.then(function() {
return this
}, function(err) {
console.log("error", err)
}
, function(msg) {
console.log("\r\n" + msg + "\r\nat " + $.now() + "\r\n")
});
return res
};
var callApi = function(instruction) {
console.log("Calling API with given instructions ..."
, instruction);
var res = $.when.apply(instruction,
$.map(instruction, function(request, key) {
return request.then(function(settings) {
return $.ajax({
type: settings.method,
dataType: settings.type,
url: settings.endpoint
});
})
})
)
.then(function(data) {
return $.map(arguments, function(response, key) {
return response[0]
})
})
return res
};
var handleResults = function(data) {
console.log("Handling data ..."
, JSON.stringify(data, null, 4));
return data
};
var run = function() {
getScenario()
.then(mapToInstruction)
.then(waitForTimeout)
.then(callApi)
.then(handleResults)
.then(run);
};
return {
// This will expose only the run method
// but will keep all other functions private
run : run
}
})($);
// ... And start the app
App.run();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
jsfiddle http://jsfiddle.net/3Lddzp9j/13/
You have a return statement in the loop in your waitForTimeout function. This means that the function is going to return after the first iteration of the loop, and that is where you are going wrong.
You're also using the deferred antipattern and are using promises in places where you don't need them. You don't need to return a promise from a then handler unless there's something to await.
The key is that you need to map each of your instructions to a promise. Array#map is perfect for this. And please use a proper promise library, not jQuery promises (edit but if you absolutely must use jQuery promises...):
var App = (function ($) {
// Gets the scenario from the API
// NOTE: this returns a promise
var getScenario = function () {
console.log('Getting scenario ...');
return $.get('http://demo3858327.mockable.io/scenario');
};
// mapToInstructions is basically unnecessary. each instruction does
// not need its own timeout if they're all the same value, and you're not
// reshaping the original values in any significant way
// This wraps the setTimeout into a promise, again
// so we can chain it
var waitForTimeout = function(data) {
var d = $.Deferred();
setTimeout(function () {
d.resolve(data.endpoints);
}, data.base.frequency);
return d.promise();
};
var callApi = function(instruction) {
return $.ajax({
type: instruction.method,
dataType: instruction.type,
url: instruction.endPoint
});
};
// Final step: call the API from the
// provided instructions
var callApis = function(instructions) {
console.log(instructions);
console.log('Calling API with given instructions ...');
return $.when.apply($, instructions.map(callApi));
};
var handleResults = function() {
var data = Array.prototype.slice(arguments);
console.log("Handling data ...");
};
// The 'run' method
var run = function() {
getScenario()
.then(waitForTimeout)
.then(callApis)
.then(handleResults)
.then(run);
};
return {
run : run
}
})($);
App.run();

Angular promises: get data from buffer if available

In this scenario the requirement is to get the data with an Http request if the data is not in a buffer. If it's in the buffer, use it from there without the Http request.
I tried the code below but it doesn't make much sense; if the data is in the buffer I don't know if I should return from the function doing nothing or return the deferred promise. Any thoughts?
var dataBuffer = null;
var getData = function() {
var deferred = $q.defer();
if (dataBuffer != null) { // this is the part I'm not convinced
deferred.resolve();
return;
}
$http.get('/some/url/')
.success(function(data) {
dataBuffer = data;
deferred.resolve();
})
.error(function(data) {
deferred.reject();
});
return deferred.promise;
};
Invoked in the following way:
var promise = getData();
promise.then (
function(response) {
dataBuffer = .... // dataBuffer contains data
}
);
There is a clean simple way to use promises when you're not sure which is the code you're executing is asynchronous or not and it's using $q.when
So the code can be:
var getData = function() {
return $q.when(dataBuffer ? dataBuffer: $http.get('/some/url'))
};
Then when calling getData you can use the same code you posted or just simply:
getData()
.then(function(response){//...
})
.catch(function(err){//..
});
Beware of the deferred antipattern. You can accomplish what you are trying to do very cleanly, like this:
var dataBuffer;
var getData = function() {
if (dataBuffer) {
// return a resolved promise for dataBuffer if it is already populated
return $q.when(dataBuffer);
}
$http.get('/some/url/')
.then(function (data) {
dataBuffer = data.data;
return dataBuffer;
});
};
getData().then(function (data) {
// data contains the data you want
})
.catch(function (error) {
// error occurred.
});
dataBuffer should not be accessed outside of your getData function. To make this perfectly clear, you can wrap them together in an IIFE, although this is optional:
var getData = (function () {
var dataBuffer;
return function() {
if (dataBuffer) {
// return a resolved promise for dataBuffer if it is already populated
return $q.when(dataBuffer);
}
$http.get('/some/url/')
.then(function (data) {
dataBuffer = data.data;
return dataBuffer;
});
};
})();
getData().then(..etc etc etc...);
As a final note, remember that you can use $http's built-in caching features, and not have to reinvent the wheel with your own buffers:
// much simpler, isn't it?
var getData = function() {
$http.get('/some/url/', { cache: true }) // enable caching
.then(function (data) { return data.data });
};
getData().then(...etc etc etc...);
Why dont you enable cache instead of handling the buffer manually.
$http.get('/some/url/',{ cache: true})
.success(function(data) {
deferred.resolve(data);
})
.error(function(data) {
deferred.reject();
});

Testing nested promises with Jasmine

This is working when I run the UI in the browser, but I'm always getting null for the 'd' in my validateAsync method that needs to call the done method to get it back to the save method. I can't figure out how to use the andCallFake (required to spyOn the unique name test), but also get it to return the (jQuery) deferred to call done on.
Hopefully this code will give you enough context to see what I'm trying to accomplish.
validateAsync = function () {
var d,
isValid = true,
isUnique = false;
// validate that name and description are given
if (layout.Name() === '') {
toastr.warning('Layout name is required', 'Layout');
isValid = false;
}
// validate that there are no other layouts of the same type with the same name
d = uiDataService.GetIsLayoutNameUniqueAsync(layout.LayoutId(), layout.Name(), layout.LayoutTypeId())
.done(function (isUniqueResult) {
isUnique = isUniqueResult.toLowerCase() === "true";
if (!isUnique) {
toastr.warning('Layout name ' + layout.Name() + ' must be unique. There is already a layout with this name.', 'Layout');
}
// this is always undefined in my Jasmine tests
d.done(isValid && isUnique);
})
.fail(function (response) {
mstar.AjaxService.CommonFailHandling(response.responseText);
});
return d;
},
save = function () {
validateAsync()
.done(function (isValidResult) {
var isValid = isValidResult.toLowerCase() === "true";
if (!isValid) {
return;
}
// show a toastr notification on fail or success
dataContext.SaveChanges(layout, uiDataService)
.done(function (layoutIdFromSave) {
toastr.success('The layout was saved. Refreshing...');
})
.fail(function () {
toastr.error('There was an error saving the layout.');
})
.always(function () {
// toastr.info('finished');
});
})
.fail(function () {
throw new Error('There was an error validating before save');
});
};
// in uiDataService
getIsLayoutNameUniqueAsync = function (layoutId, layoutName, layoutTypeId) {
return ajaxService.AjaxGetJsonAsync(webServiceUrl + "GetIsLayoutNameUnique?layoutId=" + layoutId + "&layoutName=" + escape(layoutName) + "&layoutTypeId=" + layoutTypeId);
},
// in ajaxService
ajaxGetJsonAsync = function (url, cache) {
return $.ajax({
type: "GET",
url: url,
dataType: "json",
accepts: {
json: "application/json"
},
cache: cache === undefined ? false : cache
});
},
// in a beforeEach
var getIsLayoutNameUniquePromiseSpy = spyOn(mstar.dataService.UiDataService, "GetIsLayoutNameUniqueAsync")
.andCallFake(function () {
spyObj.called = true;
// http://stackoverflow.com/questions/13148356/how-to-properly-unit-test-jquerys-ajax-promises-using-jasmine-and-or-sinon
var d = $.Deferred();
d.resolve('true');
return d.promise();
});
// and a test
it("should show a toastr", function () {
// Act
vm.GetLayout().Name('Test');
vm.GetLayout().Description('Test');
vm.Save();
// Assert
expect(toastr.success).toHaveBeenCalledWith('The layout was saved. Refreshing...');
});
Aligned, I don't know a lot about Jasmine but taking the code on its own merits, it's a lot easier to see what's going on if it's stripped right down to the bare bones.
Greatly simplified, validateAsync() is currently structured as follows :
validateAsync = function () {
...
var d = fn_that_returns_a_promise().done(function() {
...
d.done(boolean);
}).fail(function() {
...
});
return d;
};
which can't be right, because .done() doesn't accept a boolean argument and, whereas I can't say it's definitely wrong, d.done() is not really appropriate inside a d.done() handler (though maybe in different circumstances).
I suggest you want to employ .then() to filter the success case (thus passing on a new promise resolved with your boolean value), while retaining .fail() for the failure case; giving a structure as follows :
validateAsync = function () {
...
return uiDataService.GetIsLayoutNameUniqueAsync(...).then(function(...) {
...
return isValid && isUnique;
}).fail(function(...) {
...
});
};
Thus, save() can be as follows :
save = function() {
validateAsync().done(function(isValid) {
//validation success
if(!isValid) return;
...
}.fail(function() {
//validation failure
...
});
};
Now all you have to do is "join up the dots" (ie. reinsert your own statements etc) and hope I haven't made any mistakes.

Categories

Resources