我如何使这个异步 foreach 循环与 Promise 一起工作? [英] How do I make this async foreach loop work with promises?

查看:17
本文介绍了我如何使这个异步 foreach 循环与 Promise 一起工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在其中使用了 Promise,但我对它们很陌生,我只是不知道如何正确地做到这一点.目前,Promise 没有意义,因为它不会等到异步 $.get 完成.

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.

基本上,每个 foreach 迭代都有自己的 $.get 函数,我需要让它们全部完成,然后继续到具有...gets 专辑"console.log.

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

推荐答案

在同步代码中,行结束时继续执行 ;

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

使用promise,通过.then 执行延续.你使用了一个 promise 构造函数并立即解决了它,你根本没有等待任何任务.我会将我的工作映射到任务中,然后将它们与 then 链接起来或依次等待它们.

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
 });

或者更好,连续:

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

这篇关于我如何使这个异步 foreach 循环与 Promise 一起工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆