【问题标题】:How do I store functions with their parameters in an array and execute them sequentially?如何将函数及其参数存储在数组中并按顺序执行?
【发布时间】:2017-10-19 22:39:36
【问题描述】:

我正在尝试将一系列函数及其参数存储在一个数组中,然后按顺序执行它们。我一直在使用这个问题: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() 中返回了 Promise,以便稍后链接到它。

这是我承诺的 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 和 Promise 的技巧。感谢您的耐心和帮助:)

【问题讨论】:

  • 避免Promise constructor antipattern! ExecutePromiseChain 已经返回了一个承诺,BuildInventoryList 不应该使用 new Promise
  • 您的 f 似乎是一组承诺,而不是返回承诺的函数。
  • Why aren't my functions execution sequentially - 因为调用CreateRequestWPromise 会执行XMLHttpRequest

标签: javascript arrays promise


【解决方案1】:
.then(someFunction(...))

您只是调用someFunction()并将其结果传递给then()(就像任何其他参数一样)。

您需要传递一个使用您想要的参数调用它的函数:

.then(() => someFunction(...))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-26
    • 1970-01-01
    • 2015-11-09
    • 1970-01-01
    • 2019-03-08
    相关资源
    最近更新 更多