0
 getJson('data/story.json')
.then(function(){
  var answer = prompt("Do you like to break promise or keep promise?", "Yes");
  if(answer == "Yes"){
    //Promise.reject();
  }else{
    //Promise.reject();
  }
})

.then(function(story) {
  addHtmlToPage(story.heading);

  // Update the URLs for next fetch
  var chapterUrls = story.chapterUrls;
  chapterUrls = chapterUrls.map(function(url){ return "data/"+url; });

  // Take an array of promises and wait on them all
  return Promise.all(
    // Map our array of chapter urls
    // to an array of chapter json promises
    chapterUrls.map(getJson)
  );
})


.then(function(chapters) {
  // Now we have the chapters jsons in order! Loop thorugh...
  chapters.forEach(function(chapter) {
    // ..and add to the page
    addHtmlToPage(chapter.html);
    addTextToPage("One chapter is added")
  });
  addTextToPage("All done");
})

.catch(function(err) {
  // catch any error that happened along the way
  addTextToPage("Argh, broken: " + err.message);
})

.then(function() {
  document.querySelector('.spinner').style.display = 'none';
});

I just insert a new .then() block directly after the call to getJson('data/story.json').

Question: after prompt....

resolve()s itself if the user clicked “OK”, and passes the story on to the next then() block.

reject()s itself if the user clicked “Cancel”, and passes an appropriate error object with a message key containing appropriate information.

user7697691
  • 303
  • 2
  • 9
  • move the prompt inside the parentheses of your if statement, if the user click ok the prompt returns true, else it returns false meaning it goes to the else statement – Kevin Kloet Oct 03 '17 at 06:51
  • Those fulfilled/rejected promises would work if you had `return`ed them from the `then` callback – Bergi Oct 03 '17 at 11:49
  • It didnt work. i tried with return resolve(); or return resolve(story); both catch the error message – user7697691 Oct 03 '17 at 22:04

1 Answers1

-1

You can do something like this:

new Promise(function(resolve, reject) {
    getJson('data/story.json')
      .then(function() {
        var answer = prompt("Do you like to break promise or keep promise?", "Yes");
        if (answer == "Yes") {
          return resolve();
        } else {
          return reject();
        }
      });
  })
  .then(function() {
    alert('success');
  })
  .catch(function() {
    alert('error');
  });

This allows you to chain then/catch.

Frederik Hansen
  • 506
  • 4
  • 21
  • 1
    avoid the [promise constructor anti-pattern](https://stackoverflow.com/questions/23803743/what-is-the-explicit-promise-construction-antipattern-and-how-do-i-avoid-it) – Jaromanda X Oct 03 '17 at 11:17