【问题标题】:What is the 'correct way' of using fetch() within a for loop在 for 循环中使用 fetch() 的“正确方法”是什么
【发布时间】:2020-12-04 16:42:35
【问题描述】:

如果我使用它进行获取,我无法理解我的 for 循环需要去哪里。我的代码依赖于所有被解析的承诺并将 JSON 数据保存到testarray

我进行了各种尝试,但都没有解决我的问题。一种是 for 循环调用一个包含 promise 的函数。

function getData() {
        return new Promise(function (resolve, reject) {
            fetch(url[i])
                .then((resp) => resp.json())
                .then(function (data) {
                    buffer = data;
                    resolve();
                });
        });
}

for (i = 0; i <2; i++){
    getData().then(function(){
    testarray.push(buffer);
    //do stuff with testarray
    })
    
}

但这不起作用,因为我无法使用在testarray 上推送的数据,除非它在 ​​for 循环块中。

如果我将 for 循环放在 promise 或 fetch 周围,我会遇到类似的问题。

所以我的问题是。如果您使用 for 循环通过 API 调用获取各种 JSON,您如何使用 for 循环之外的数据?我需要对数据执行的所有操作都需要完成。

我很困惑,因为我觉得 Javascript 迫使我将与数据相关的操作或代码放在我的评论所在的位置。这正常吗?

【问题讨论】:

  • 考虑使用 async-await 并将i 传递给getData
  • 承诺全部或等待 /async
  • 这能回答你的问题吗? link
  • 谢谢大家,我将使用异步等待。非常感谢@mpgbk 的链接。

标签: javascript arrays json asynchronous promise


【解决方案1】:

您有Promise.all API 来解决您的问题。此方法将执行所有传递给它的 Promise,并且在所有 Promise 都正常之前不会解析。

这与async/await 一起可能是解决您问题的好方法:

async function forFetch(){
    let urls = [/* your urls */], fetches = [];

    for(let url of urls){ 
        fetches.push(fetch(url));
    }
    
    let results = await Promise.all(fetches);
    return results; //do whatever you want with your results like converting them to json.
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-31
    • 1970-01-01
    相关资源
    最近更新 更多