等待循环中的异步函数在下一次迭代之前完成执行 [英] wait for async function in loop to finish executing before next iteration

查看:35
本文介绍了等待循环中的异步函数在下一次迭代之前完成执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组要异步下载的图像 url.我需要等待下一次迭代,直到第一个异步任务完成.这是我的代码片段:

I have an array of image urls to download asynchronously. I need to wait the next iteration until the first async task completed. Here is my code snippet:

 downloadQueue.forEach(function (download, idex) {

        download.startAsync().then(
            function (res) { console.log('onSuccess'); },
            function (err) { console.log('onError'); },
            function (msg) {
                var progressPrecent = parseFloat(msg.bytesReceived / msg.totalBytesToReceive * 100).toFixed(2);
                console.log('Progress: ' + progressPrecent);
            });
    });

第一个 url 下载完成后,应该开始下一个(迭代).我应该如何修改此代码以进行处理?任何帮助..

After download completion of the first url, next one(iteration) should be started. How should i modified this code to get work on that? Any help..

推荐答案

你会想要做一些递归的事情.

You will want to do something recursive.

这样,您只能在下载返回 Promise 后才开始下一次下载.

That way you only start the next download after the promise returns from the download.

//Declare the recursive function
var startDownload = function(downloadQueue,i) {
    download.startAsync().then(
        function (res) { console.log('onSuccess'); },
            function (err) { console.log('onError'); },
            function (msg) {
            var progressPrecent = parseFloat(msg.bytesReceived / msg.totalBytesToReceive * 100).toFixed(2);
            console.log('Progress: ' + progressPrecent);

            //If there are more items to download call startDownload
            if(i < downloadQueue.length) {
               startDownload(download,i+1);
            }
    });
}

//Initialize Function
startDownload(downloadQueue,0);

这篇关于等待循环中的异步函数在下一次迭代之前完成执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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