本文地址: http://www.cnblogs.com/jasonxuli/p/4398742.html
下午的太陽曬得昏昏沉沉,和上周五一樣迷糊,看一段代碼半天沒看明白,剛才不知不覺眯了幾分鍾,醒來后再看就醒悟了。
這段代碼先加載story.json文件,然后依次加載story.chapterUrls數組中的url。看半天一直沒搞明白為啥是順序的,原因是每個reduce執行的function本身就構造了first - next的順序結構,而Promise的then又保證了代碼的順序執行,即reduce把多個then串起來生成了一長串then。
getJson('story.json').then(function(story) {
addHtmlToPage(story.heading);
return story.chapterUrls.reduce(function(chain, chapterUrl) {
console.log('reduce ', chain, chapterUrl);
// Once the last chapter's promise is done…
return chain.then(function() {
// …fetch the next chapter
return getJson(chapterUrl);
}).then(function(chapter) {
// and add it to the page
addHtmlToPage(chapter.html);
});
}, Promise.resolve());
}).then(function() {
// And we're all done!
addTextToPage("All done");
}).catch(function(err) {
// Catch any error that happened along the way
addTextToPage("Argh, broken: " + err.message);
}).then(function() {
// Always hide the spinner
document.querySelector('.spinner').style.display = 'none';
});
上周五看bluebird的代碼,想找出Promise.promisify()是怎么做到把異步回調式的函數變成Promise式的函數。看了半天,發現它把目標函數的最后一位參數當做callback,並且把這個callback函數的第一位參數當做err。原來是有前置條件的,那么好像沒我想的那么強大嘛。迷糊的時候又去看了下bluebird的md文檔,原來人家早就說了:
The node function should conform to node.js convention of accepting a callback as last argument and calling that callback with error as the first argument and success value on the second argument.
