我正在尝试完成以下方法:
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
最终成为一个空数组,因此推送的值会以某种方式被删除
如何让它做我想做的事?
编辑:我不想在这里使用承诺。答案 0 :(得分:2)
您正在测试错误位置的结果
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循环中使用let,以便{/ 1}}在
中正确不要i
...分配到索引,以保留结果的顺序
另类,通过&#34;宣传&#34; push
(在下面的代码中称为getValue
)
getValuePromise
答案 1 :(得分:-2)
您需要做的是使用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)
}
})
}