使用异步方法调用在ES6中创建数组



我有以下我要完成的方法:

  getAllValues: function (callback) {
    this.getCount((count) => { // count is usually 5
      let results = []
      for (var i = 0; i < count; i++) {
        this.getValue(i, (result) => { // getValue() is async and eventually returns a string
          results.push(result)
        })
        if (i == count-1) {
          callback(results)
        }
      }

我希望 results成为一个数组,其中 getValue()返回的所有字符串;但是,我无法弄清楚如何做到这一点。在callback(results)中,results最终是一个空数组,因此推动的值以某种方式删除

我该如何做我想做的事情?

编辑:我不想在这里使用承诺。

您正在测试错误的地方的结果

getAllValues: function(callback) {
    this.getCount((count) => { // count is usually 5
        let results = [];
        let completed = 0;
        for (let i = 0; i < count; i++) { // *** use let instead
            this.getValue(i, (result) => { // getValue() is async and eventually returns a string
                completed ++;
                results[i] = result; // *** note this change to guarantee the order of results is preserved
                if (completed == count) {
                    callback(results)
                }
            })
        }
    })
}

注意:使用让for for循环,以便 i

内是正确的

不要push ...分配给索引,以保留结果的顺序

和替代方案,通过具有" promified" getValue(在下面的代码中称为getValuePromise

getValuePromise: function(i) {
    return new Promise(resolve => {
        this.getValue(i, resolve);
    });
}
getAllValues: function(callback) {
    this.getCount((count) => 
        Promise.all(Array.from({length:count}).map((unused, i) => this.getValuePromise(i)))
        .then(callback)
    );
}

您需要做的是使用then(),它将等待您的异步函数完成,然后运行您的回调。

getAllValues: function (callback) {
    this.getCount((count) => { // count is usually 5
      let results = []
      for (var i = 0; i < count; i++) {
        this.getValue(i, (result) => { // getValue() is async and eventually returns a string
          results.push(result)
        }).then(function(getValueResults){
            if (i == count-1) {
              callback(results)
            }
        })
      }

最新更新