Using deferred with a snippet

  • 1
  • Question
  • Updated 2 years ago
Trying to call multiple snippets within a snippet. the child snippets have calls like save() or updateData() inside them. So you could see how calls from the first snippet may actually finish after the second and so on.

I'm wondering if there is a way to wrap the getSnippet inside a $.when  .done and leverage deferred() promise multiple times in the parent snippet. Anyone have an example or thoughts on this?
Photo of Brett

Brett

  • 80 Points 75 badge 2x thumb

Posted 2 years ago

  • 1
Photo of Zach McElrath

Zach McElrath, Employee

  • 49,056 Points 20k badge 2x thumb
If you have a parent snippet that calls multiple asynchronous functions or other snippets within it, then I'd absolutely advise you to leverage Promises to ensure that your logic is appropriately waiting for asynchronous code to finish before moving on.

One key thing to know is that "save()" and "updateData()" already return Promises, so if you have a snippet that ends with a call to either of these, then you can just return the result of the save() or updateData() call and it will be a Promise. 

Also, these methods can be chained using .then(), for instance

// In a snippet...
return myModel.save()
.then(function(){
   return myModel.updateData();
})
.then(function(){
   return anotherModel.save();
})
.then(function(){
   return anotherModel.updateData();
});
Photo of Brett

Brett

  • 80 Points 75 badge 2x thumb
Hey Zach, thanks so much for helping me. Still trying to get this to work right. Am pretty close but the snippet on the return is still giving me some trouble. Snippet has a $.Deferred() & returns a promise but it continues onto the next call before the promise is resolved. is there something I'm missing here?

how I'm calling the snippet in the then
.then(function(){
    console.log('retrieve otm then');
    return skuid.snippet.getSnippet('retrieveOTMD')();
   })
(Edited)