I've been beating my head against $.Deferred and Promises for awhile now, ever since working on Rebecca Murphey's JS Assessment. I think I managed to stumble through the assessment, but I didn't really understand what I was doing. I just knew that Deferred/Promises were used for async management... I think.
Since then, I didn't really think to bother using Deferred/Promise until working on a project for work today. I wanted to do something like the following:
Get a session key via ajax
When successful, use the key to instantiate the client
Get a list of objects according to some criteria (this would be done asynchronously, via an API)
From that list of objects, load some kind of media
All the articles I read today used ajax/xhr as a prime example, which was helpful for my ajax call. However, I was pretty clueless how to Deferred/Promise-ize the call that asynchronously loads the objects through the API. After some trial and error, here's what I came up with:
Since then, I didn't really think to bother using Deferred/Promise until working on a project for work today. I wanted to do something like the following:
Get a session key via ajax
When successful, use the key to instantiate the client
Get a list of objects according to some criteria (this would be done asynchronously, via an API)
From that list of objects, load some kind of media
All the articles I read today used ajax/xhr as a prime example, which was helpful for my ajax call. However, I was pretty clueless how to Deferred/Promise-ize the call that asynchronously loads the objects through the API. After some trial and error, here's what I came up with:
var step1 = $.ajax(...); step1.done(... instantiate client ...); step1.fail(... failed ...); var step2 = step1.then( function(data) { return getListAsync(); }, function(err) {} ); var step3 = step2.then( function(data) { return loadData(data); }, function(err) {} ); function getListAync() { var def = $.Deferred(); def.done(function(result) { // do some stuff return result.objects; }); var callback = function(args) { def.resolve(args); }; theAsyncAPI.someCall(callback, arg1, arg2, arg3); return def.promise(); }I have no idea if there is a better way to do this, so hopefully as I keep working on this, I'll figure it out better. At least it doesn't seem so confusing now. :)
Comments
Post a Comment