【问题标题】:Building a dynamic array of functions for Q.all() in Jscript在 Jscript 中为 Q.all() 构建动态函数数组
【发布时间】:2013-10-18 00:14:05
【问题描述】:

我正在尝试将可变数量的函数传递给 Q.all()

如果我手动对数组进行编码,它可以正常工作 - 但是我想在循环中构建它,因为系统不知道在运行时之前调用函数多少次 - 并且需要为每个 AJAX 传递不同的 ID打电话。

我尝试了各种方法都没有成功(例如array[i] = function() {func}) - 我猜eval() 可能是最后的手段。

任何帮助都会非常有帮助。

// Obviously this array loop wont work as it just executes the functions in the loop
// but the idea is to build up an array of functions to pass into Q
var arrayOfFunctions = [];

for(var i in NumberOfPets) {
    arrayOfFunctions[i] = UpdatePets(i);
}


// Execute sequence of Ajax calls
Q.try(CreatePolicy)
.then(updateCustomer) 
.then(function() {

    // This doesn't work - Q just ignores it
    return Q.all(arrayOfFunctions)

    // This code below works fine (waits for all pets to be updated) - I am passing in the ID of the pet to be updated
    // - But how can I create and pass in a dynamic array of functions to achieve this?
    // return Q.all([UpdatePets(1), UpdatePets(2), UpdatePets(3), UpdatePets(4), UpdatePets(5), UpdatePets(5)]);

    }) 
.then(function() {
    // do something
})
.catch(function (error) {
    // error handling
})
.done();

提前致谢。

【问题讨论】:

  • 成功的手动版是什么样子的?
  • 当然,Q.all() 接受一组承诺,而不是一组函数。

标签: javascript arrays promise deferred q


【解决方案1】:

Q.all 不期望函数数组,而是承诺数组。使用

Q.try(CreatePolicy)
.then(updateCustomer) 
.then(function() {
    var arrayOfPromises = [];
    var numberOfPets = pets.length;
    for (var i=0; i<numberOfPets; i++)
        arrayOfPromises[i] = updatePet(pets[i], i); // or something
    return Q.all(arrayOfPromises)
}) 
.then(function() {
    // do something
})
.catch(function (error) {
    // error handling
});

【讨论】:

  • 谢谢你——这成功了——我可能需要对这个主题做更多的阅读——可能是运气我已经走到了这一步!
猜你喜欢
  • 2021-11-13
  • 2014-08-30
  • 2019-12-07
  • 2012-01-30
  • 1970-01-01
  • 1970-01-01
  • 2017-07-24
  • 1970-01-01
  • 2017-04-18
相关资源
最近更新 更多