【问题标题】:html fetch multiple fileshtml 获取多个文件
【发布时间】:2015-06-22 23:01:29
【问题描述】:

我想使用新的 fetch api (https://fetch.spec.whatwg.org/) 一次获取多个文件。原生可以吗?如果是这样,我应该如何利用承诺?

【问题讨论】:

    标签: html standards fetch-api


    【解决方案1】:
    var list = [];
    var urls = ['1.html', '2.html', '3.html'];
    var results = [];
    
    urls.forEach(function(url, i) { // (1)
      list.push( // (2)
        fetch(url).then(function(res){
          results[i] = res.blob(); // (3)
        })
      );
    });
    
    Promise
      .all(list) // (4)
      .then(function() {
        alert('all requests finished!'); // (5)
      });
    

    这是未经测试的代码! 此外,它依赖于 Array.prototype.forEach 和 ES6 的新 Promise 对象。这个想法是这样的:

    1. 遍历所有 URL。
    2. 对于每个 URL,使用 fetch API 获取它,将返回的 Promise 存储在 list 中。
    3. 另外,当请求完成后,将结果存储在results中。
    4. 创建一个新的 Promise,当 list 中的所有 Promise 都已解决(即所有请求都已完成)时,该 Promise 将解决。
    5. 享受充满活力的results

    【讨论】:

    • 太棒了!我现在就测试一下,如果有什么问题告诉你!!谢谢
    • 酷! (毕竟,这是我第一次结合使用所有这些东西。很高兴看到,我的 JS 直觉仍然适用于 ES6 领域......)
    【解决方案2】:

    在 Kotlin 中实现 Boldewyn's solution 时,我将其缩减为:

    fun fetchAll(vararg resources: String): Promise<Array<out Response>> {
        return Promise.all(resources.map { fetch(it) }.toTypedArray())
    }
    

    这在 JavaScript 中大致翻译为:

    function fetchAll(...resources) {
        var destination = []
        resources.forEach(it => {
            destination.push(fetch(it))
        })
        return Promise.all(destination)
    }
    

    之前,我尝试使用 map 而不是 forEach + pushing 到一个新数组,但由于某种原因根本不起作用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-06
      • 2019-04-17
      • 2010-10-29
      • 2014-08-09
      • 2010-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多