提示用户违背承诺或履行承诺

时间:2017-10-03 06:49:36

标签: javascript promise

 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';
});

我只是在调用getJson('data / story.json')之后直接插入一个新的.then()块。

问题: 提示后......

如果用户单击“确定”,则

resolve()s本身,并将故事传递给下一个 然后()阻止。

如果用户单击“取消”,则拒绝()s本身,并传递相应的错误 带有包含适当信息的消息密钥的对象。

1 个答案:

答案 0 :(得分:-1)

您可以这样做:

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');
  });

这允许你链接/ catch。