简体   繁体   English

从数组顺序执行一堆WinJS Promise

[英]Sequentially execute a bunch of WinJS promises from an array

I have an array of URLs that I want to download sequentially, 2 URLs at the time. 我有一个要依次下载的URL数组,当时是2个URL。

var urls = [url1,url2,url3,url4,url5];

The loop should download all the URLs using some async function, 2 urls at the time in the order they appear in the array. 循环应使用一些异步功能下载所有URL,每次2个url按它们在数组中出现的顺序。 The basic sequential loop is done using .reduce that works like this: 基本顺序循环是使用.reduce来完成的,其工作方式如下:

preloadPromise = urls.reduce(function(p, url) {
  return p.then(WinJS.Utilities.Scheduler.schedulePromiseBelowNormal).then(function() {
    return preloadOneAsync(url);
  }).then(null, function(error) {
    if (error.name !== "Canceled") {
      logger.error("Could not create preloaded " + url, error);
    }
  });
}, WinJS.Promise.as());

Now I want to introduce parallel downloads of 2 URLs at the same time. 现在,我想同时介绍两个URL的并行下载。

So it would download: [url1,url2] then [url3,url4] and finally [url5] 因此它将下载:[url1,url2]然后[url3,url4],最后是[url5]

Also the result of the function should be the results of every download promise, similar to how WinJS.Promise.join works. 函数的结果也应该是每次下载承诺的结果,类似于WinJS.Promise.join工作方式。

Let's abstract out the function to break the array into tuples 让我们抽象出将数组分解为元组的函数

function chunkBy(array, n) {
    var chunks = [];
    for (var i=0; i<array.length; i+=n)
        chunks.push(array.slice(i, n));
    return chunks;
}

and the function that does the work for each item: 以及对每个项目起作用的函数:

function tryToLoad(url) {
    return WinJS.Utilities.Scheduler.schedulePromiseBelowNormal() // not sure
    .then(function() {  return preloadOneAsync(url); })
    .then(null, function(error) {
        if (error.name !== "Canceled") {
            logger.error("Could not create preloaded " + url, error);
        }
    });
}

A function that does the work for multiple items in parallel would be just 一个可以并行处理多个项目的函数就是

function loadAll(urls) {
    return WinJS.Promise.join(urls.map(tryToLoad));
}

so we can now use this in the generation of the sequence: 现在我们可以在生成序列时使用它:

preloadPromise = chunkBy(urls, 2).reduce(function(p, urls) {
    return p.then(function(prevResults) {
        return loadAll(urls).then(function(results) {
            return prevResults.concat(results);
        });
    });
}, WinJS.Promise.as([]));

The array of results is passed through the p chain, always growing after each step. 结果数组通过p链传递,始终在每个步骤之后增长。

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

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