2017-10-19 57 views
0

我想將一系列函數與它們的參數存儲在一個數組中,然後順序執行它們。我一直在使用這個問題:How to chain execution of array of functions when every function returns deferred.promise? 並對此問題的具體答案:http://plnkr.co/edit/UP0rhD?p=preview如何將函數的參數存儲在數組中並按順序執行?

從我的理解,這可以用對象文字或數組來完成。我讀過一些人們在數組中存儲沒有參數的函數的問題,但到目前爲止還沒有找到一個好的答案來將它們包含在參數中。

以下是我的嘗試。我首先創建一個帶參數的函數數組(現在用硬編碼),然後將它們傳遞給ExecutePromiseChain()以供執行。從我看到的看起來,函數立即被調用,這是我不想要的。

Responses = []; 
function BuildInventoryList(){ 
    return new Promise(function(resolve, reject) { 
     f = [new CreateRequestWPromise(`https://${defaults.host}/inventory/88421`, {}), 
    new CreateRequestWPromise(`https://${defaults.host}/inventory/19357`,{})]; 

     resolve(ExecutePromiseChain(f)); 
}); 
} 

function ExecutePromiseChain(funcs){ 
    var promise = funcs[0]; 
    for (var i = 1; i < funcs.length; i++){ 
     promise = promise.then(funcs[i]); 
    } 
    return promise; 
} 

請注意,我在回國承諾ExecutePromiseChain(),所以我可以鏈,它以後。

這是我promisified http請求功能:

function CreateRequestWPromise(url, body){ 
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest; 

return new Promise(function(resolve, reject) { 
    var xhr = new XMLHttpRequest(); 
     xhr.onload = function(){ 
      if(xhr.status == 200){ 
       Responses.push(JSON.parse(xhr.response)); 
       resolve(xhr.responseText); 
      } 
      else{ 
       reject(xhr.statusText); 
      } 
     } 
     xhr.onerror = function() { 
      reject(Error("Network Error")); 
     }; 

    xhr.open("POST", url); 
    xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8'); 
    var bodyS = JSON.stringify(body); 
    xhr.send(bodyS); 
}); 
} 

我調用這些函數在與程序的啓動:

BuildInventoryList().then(CreateRequestWPromise(`https://${defaults.host}/inventory/update`, 
    Items)); 

那麼愚蠢的錯誤,我在這裏做?爲什麼我的函數不能按順序執行?

由於可能很明顯,我還在學習Javascript和承諾的繩索。我很欣賞的耐心和幫助:)

+0

避免['Promise'構造反模式](https://stackoverflow.com/q/23803743/1048572?What -is最諾言建設,反模式和如何對避免-吧)! 'ExecutePromiseChain'已經返回一個promise,'BuildInventoryList'不應該使用'new Promise'。 – Bergi

+0

你的'f'似乎是一組promise,而不是返回promise的函數。 – Bergi

+0

'爲什麼我的函數不能順序執行 - - 因爲調用'CreateRequestWPromise'執行'XMLHttpRequest' –

回答

0
.then(someFunction(...)) 

你剛纔稱爲someFunction(),並通過其結果then()(就像任何其他參數)。

您需要傳遞與調用的參數是一個函數,你想:

.then(() => someFunction(...)) 
相關問題