本文地址: http://www.cnblogs.com/jasonxuli/p/4398742.htmlhtml
下午的太陽曬得昏昏沉沉,和上週五同樣迷糊,看一段代碼半天沒看明白,剛纔不知不覺眯了幾分鐘,醒來後再看就醒悟了。node
這段代碼先加載story.json文件,而後依次加載story.chapterUrls數組中的url。看半天一直沒搞明白爲啥是順序的,緣由是每一個reduce執行的function自己就構造了first - next的順序結構,而Promise的then又保證了代碼的順序執行,即reduce把多個then串起來生成了一長串then。json
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.promise