简体   繁体   English

如何使用异步功能解决以下问题

[英]How do I solve the following issue with async function

I have a javascript array. 我有一个javascript数组。 I need to process each element of this array and then store the entire array into an object store. 我需要处理此数组的每个元素,然后将整个数组存储到对象存储中。 The kind of processing I do on the elements should be async. 我对元素进行的处理应该是异步的。 as shown in the following method. 如以下方法所示。

var x = [ele1,ele2,ele3] ; 

x.forEach(function(ele,index){

if(ele == "some specific object"){
MyAPI.process("command",function(result){ 

x[index] = result; 
});

database.store(x); 

The problem when calculating asynchronously is that the elements aren't processed in order. 异步计算时的问题是,元素未按顺序处理。 The key would be to keep track of the number of results that have been processed then, and only then, call the store method. 关键是要跟踪当时已处理的结果数,然后才调用store方法。 The most effective way is to move the call to the store method into the callback. 最有效的方法是将对store方法的调用移到回调中。 That way you can call it directly after the check for the last element succeeds rather than having to do a busy/wait while checking the flag condition. 这样,您可以在检查最后一个元素成功之后直接调用它,而不必在检查标志条件时进行忙/等待。 Another possibility would be to raise an event when the last element is processed and have the store take place in the event handler (or something similar). 另一种可能性是在处理完最后一个元素并在事件处理程序(或类似操作)中进行存储时引发事件。

var x = [ele1,ele2,ele3] ; 
var expectedResults = 0;
var results = 0;

x.forEach(x,function(ele,index) {
     if (ele == "some specific object") {
         ++expectedResults;
     }
});

x.forEach(x,function(ele,index){

    if (ele == "some specific object"){
        MyAPI.process("command",function(result){ 
           x[index] = result;
           if (++results == expectedResults) {
              database.store(x);
           }
        });
    }
});

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM