2017-10-03 9 views
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'; 
}); 

getJson( 'data/story.json')の呼び出しの直後に新しい.then()ブロックを挿入するだけです。約束を破るか約束を守るようにユーザーに促す

質問:プロンプトの後 ....

決意は()ユーザーが「OK」クリックした場合は、それ自体だ、と次の その後、()ブロックの上で話を渡します。

ユーザーが「キャンセル」をクリックした場合、適切なエラーメッセージ を適切な情報を含むオブジェクトに渡します。

+0

プロンプトをif文のかっこ内に移動します。ユーザがOKをクリックするとプロンプトがtrueを返し、そうでない場合はfalseが返されてelse文に移動します。 –

+0

'return'edそれらから 'then'コールバック – Bergi

+0

それは仕事をしなかった。私はリターンresolve()で試した。または返品解決(ストーリー)。どちらもエラーメッセージ – user7697691

答えて

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

+0

を受け取っています。動作していません。とにかくエラーマッサージをキャッチ – user7697691

+0

更新しました。これはうまくいくはずです。 –

+1

[promiseコンストラクタのアンチパターン]を避けてください(https://stackoverflow.com/questions/23803743/what-is-the-explicit-promise-construction-antipattern-and-how-do-i-avoid-it) –