简体   繁体   English

如何将函数及其参数存储在数组中并顺序执行?

[英]How do I store functions with their parameters in an array and execute them sequentially?

I'm trying to store a series of functions in an array with their parameters, and then execute them sequentially. 我试图将一系列函数及其参数存储在数组中,然后依次执行它们。 I've been using this question: How to chain execution of array of functions when every function returns deferred.promise? 我一直在使用这个问题: 当每个函数返回deferred.promise时,如何链接函数数组的执行? And a specific answer to this question: http://plnkr.co/edit/UP0rhD?p=preview . 以及该问题的具体答案: http : //plnkr.co/edit/UP0rhD?p=preview

From my understanding this can be done with an object literal or an array. 据我了解,这可以通过对象文字或数组来完成。 I've read some questions where people store functions without parameters in arrays, but so far haven't found a good answer on including them with parameters. 我已经读了一些问题,人们在其中将没有参数的函数存储在数组中,但是到目前为止,还没有找到将参数包括在内的好答案。

Below is my attempt. 以下是我的尝试。 I'm creating an array of functions with their parameters first (hard-coded for now), and then I pass them to ExecutePromiseChain() for execution. 我先创建一个带有参数的函数数组(目前为硬编码),然后将它们传递给ExecutePromiseChain()以执行。 From what I see it looks like the functions are called immediately, which I don't want. 从我看来,这些函数似乎立即被调用了,这是我不想要的。

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

Note that I'm returning promise in ExecutePromiseChain() so I can chain to it later. 请注意,我在ExecutePromiseChain()中返回了promise,因此以后可以链接到它。

And this is my promisified http request function: 这是我承诺的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);
});
}

I call these functions at the start of the program with: 我在程序开始时使用以下命令调用这些函数:

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

So what dumb mistakes am I making here? 那我在这里犯了什么愚蠢的错误呢? Why aren't my functions execution sequentially as they should be? 为什么我的函数没有按顺序执行?

As is probably obvious I'm still learning the ropes of Javascript and promises. 很明显,我仍在学习Javascript和Promise的绳索。 I appreciate the patience and help :) 感谢您的耐心配合和帮助:)

.then(someFunction(...))

You just called someFunction() and pass its result to then() (just like any other parameter). 您只需调用 someFunction()并将其结果传递给then() (就像其他任何参数一样)。

You need to pass a function that calls it with the parameters you want: 您需要传递一个使用所需参数调用它的函数:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何按顺序执行承诺,从数组传递参数? - How to execute promises sequentially, passing the parameters from an array? 用参数执行数组中的函数 - Execute functions in array with parameters 在将变量添加到数组时如何将变量传递给函数 - How do I pass variables to functions while adding them into an array jQuery按顺序执行函数 - JQuery execute functions sequentially 如何在数组中存储Object的函数指针? - How do I store an Object's functions pointers in an array? Promise.all()是执行函数数组还是在将它们放入数组时执行它们? - Does Promise.all() execute an array of functions or do they execute when you put them into the array? 如何依次运行多个功能,并在其中任何一个出现故障时停止所有功能? - How can I run multiple functions sequentially, and stop all when any of them fail? 如何基于输入参数数组在函数内部执行函数? - How can I execute functions inside a function based on an array of input parameters? 用于顺序执行承诺函数的未知长度数组 - Unknown length array used to execute promised functions sequentially Javascript:将函数(带有参数)添加到数组并在onload事件触发时执行它们 - Javascript: add functions (with parameters) to array and execute them when onload event fires
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM