简体   繁体   中英

How do I convert this code to chained promises?

I want to create a JS code to create many nested pages. Here is an example with creating 5 nest pages (5 depth levels)

var self = this;
var parentPageId = 1; // this is initial data. 

// 1
this._genPage(spaceKey, parentPageId).done(function (createdPage) {
    // 2
    self._genPage(spaceKey, createdPage.id).done(function (createdPage) {
        // 3
        self._genPage(spaceKey, createdPage.id).done(function (createdPage) {
            // 4
            self._genPage(spaceKey, createdPage.id).done(function (createdPage) {
                // 5
                self._genPage(spaceKey, createdPage.id).done(function (createdPage) {
                Util.showSuccessMessage('Data Generated: 5 nested pages');
            });
        });
    });
});

How do I convert above code to create any number of nest pages? Currently, I am using jQuery. It is fine if you suggest any Promise library to solve this problem.

Thank you.

promises are designed to be chained, what you return from one done is resolved by the next done in the chain:

this._genPage(spaceKey, parentPageId)
    .done(function (createdPage) {
       return self._genPage(spaceKey, createdPage.id);
    }).done(function (createdPage) {
       return self._genPage(spaceKey, createdPage.id);
    }); // etc

Some simple recursion (or even a loop) can be done to make this any number of levels deep.

function genPagesRecursive(spaceKey, id, depth){
   if(depth == 0){
      return 'Data Generated';
   }

   return self._genPage(spaceKey, id).done(function(createdPage){
       return genPagesRecursive(spaceKey,id,--depth);
   })
}

You can even chain another done on the call to the recursive method:

genPagesRecursive(spaceKey, creadtedPage.id, 5).done(function(msg){
     Util.showSuccessMessage(msg);          
});

Simple recursion will do.

function createNestedPages(spaceKey, parentPageId, numberOfPages) {
  if (numberOfPages <= 0) {
    return;
  }

  this._genPage(spaceKey, parentPageId).done(function (createdPage) {
     createNestedPages(spaceKey, createPage.id, numberOfPages - 1);
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM