仅在for循环中执行了所有异步函数之后,才执行函数

时间:2018-09-17 19:02:40

标签: javascript arrays

关于堆栈溢出的问题,这里有不同的答案,但是我仍然无法使其正常工作。有人可以让我知道是什么错误或更好的解决方法

array = [[name1,value1],[name2,value2] ;
for (var i = 0; i < array.length; i++) {
    name = array[i][0];
    value = array[i][1];
    //the below is the async function in tableau javascript
    worksheet.applyFilterAsync(name, value, 'ADD')

    if (i = array.length - 1) {
       addEventListener = () => {
           callbackfunction();
       }
    }
}

1 个答案:

答案 0 :(得分:0)

您可以使用Promise.all等待所有诺言得到解决,如果至少一个诺言引发了拒绝,则拒绝:

var array = [[name1,value1],[name2,value2]];

// .map returns an array of promises
var promises = array.map(([name, value], i) => {
    //the below is the async function in tableau javascript
    return worksheet[i].applyFilterAsync(name, value, 'ADD');
});

promises[promises.length - 1].then(() => {
    // Do stuff after the last promise is resolved
});

// Waits for all promises to resolve
Promise.all(promises).then(() => {
    // Do stuff after all promises are resolved
});