How do I make this async foreach loop work with pr

2020-02-02 08:55发布

问题:

I've already messed around with Promises in it, but I'm new to them and I just can't figure out how to do it properly. At the moment, there's no point to the Promise, because it doesn't wait till the async $.get completes.

Basically, each foreach iteration has its own $.get function, and I need to have them all complete and then continue to the part that has the "...gets albumart" console.log.

$.get(id,function(data) {
    //(there's some code here)
    var getZippyUrls = new Promise(function(resolve) {
            zippyarray.forEach(function(zippy) {
            //(more code)
            $.get(zippy.full, function(data) {
                //^This is the foreach of $.gets
               //(code's here)
            });  
           resolve(zippyarray);
        });
    });

    //This is my failed Promise ->
    getZippyUrls.then(function(response) {
        console.log("WE'RE OUT " + response.length);
        response.foreach(function(d) {
            console.log("Promise"+d.media);
        });
        console.log('eyyyyyy');
    });

    console.log("...gets albumart");
    //Now after the previous stuff is done, move on

回答1:

In synchronous code, continuation is performed when the line ends ;

With promises, continuation is performed via .then. You were using a promise constructor and resolved it immediately, you did not wait for any task at all. I'd map my work into tasks and then either chain them with then or await them serially.

//I'm assuming
zippyarray; // array of Zippy objects

var tasks = zippyarray.map(function(zippy,i){
    return function(){ // return a task on that zippy;
       // basic logic here
       return $.get({
            // ajax request
       }).then(function(data){
            // process data like in your code
            // possibly store later for later use too
            return process(data); // return the processed data;
       });
    }
});

Now we can execute them all sequentially:

 var p = tasks[0](); // start the first one
 for(var i = 1; i < tasks.length; i++) p = p.then(tasks[i]);
 p.then(function(result){
       // all available here
 });

Or better, serially:

$.when.apply(tasks.forEach(function(t){ return t(); })).then(function(results){
     // all done
})


回答2:

I know this is an old question but things have changed a bit recently.

If you're fine with using external libraries, the Bluebird promise library has a pretty good implementation for this: Promise.each.

E.g.

function helperFunc(zippyarray) {
  return Promise.each(zippyarray, zippy => {
    return someOperationThatReturnAPromise(zippy)
      .then((singleResult) => {
        // do something with the operation result if needed
      })
  }).then((originalArray) => {
    // this happens only after the whole array is processed
    // (result is the original array here)
    return Promise.resolve(originalArray)
  })
}


回答3:

To keep track of multiple get-Requests you are using this way:

var cnt = requestCnt;

function finished(){
    if(--cnt)return;
    // Your code here
}

for(var i = 0; i < requestCnt; ++i){
    $.get('something.htm', {data:data}, function(data){
        finished();
    });
}

You always call the finished-function when a request gets an answer. The finished-function does the job when all gets done.



回答4:

Today if I needed to do it sequentially - I would do it with async/await:

//I'm assuming I'm inside an `async` function
zippyarray; // array of Zippy objects

for(const task of zippyArray) {
  const result = await $.get({ ... });
  // do stuff with result
}