gpt4 book ai didi

javascript - 在 JavaScript 中使用 for 循环创建一系列异步获取序列

转载 作者:行者123 更新时间:2023-12-03 09:17:57 25 4
gpt4 key购买 nike

我有一些 JSON 格式的文件,它们的名称如下所示:

chapter1.json,chapter2.json,chapter3.json,...

我想在 javascript 中使用 Promises 获取文件的内容,并在 HTML 页面中按顺序显示它们。但我不想重复 then() 方法。相反,我想使用 for 循环。我不想使用node.js。

谁能帮我解决这个问题吗?非常感谢。

最佳答案

我找到了答案。

function get(url) {
// Return a new promise.
return new Promise(function (resolve, reject) {
// Do the usual XHR stuff
var req = new XMLHttpRequest();
req.open('GET', url);

req.onload = function () {
// This is called even on 404 etc
// so check the status
if (req.status == 200) {
// Resolve the promise with the response text
resolve(req.response);
}
else {
// Otherwise reject with the status text
// which will hopefully be a meaningful error
reject(Error(req.statusText));
}
};

// Handle network errors
req.onerror = function () {
reject(Error("Network Error"));
};

// Make the request
req.send();
});
}
function getJSON(url) {
return get(url).then(JSON.parse);
}
$(function () {
getJSON('story.json').then(function(story) {
$("#message").append(story.heading);

// Take an array of promises and wait on them all
return Promise.all(
// Map our array of chapter urls to
// an array of chapter json promises
story.chapterUrls.map(getJSON)
);
}).then(function(chapters) {
// Now we have the chapters jsons in order! Loop through…
chapters.forEach(function(chapter) {
// …and add to the page
$("#message").append(chapter.html);
});
$("#message").append("All done");
}).catch(function(err) {
// catch any error that happened so far
$("#message").append("Argh, broken: " + err.message);
}).then(function() {
document.querySelector('.spinner').style.display = 'none';
});
});

story.json 是:

{
"heading": "<h1>A story about something</h1>",
"chapterUrls": [
"chapter-1.json",
"chapter-2.json",
"chapter-3.json",
"chapter-4.json",
"chapter-5.json"
]
}

此代码首先并行获取所有章节,然后按顺序显示它们。

关于javascript - 在 JavaScript 中使用 for 循环创建一系列异步获取序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31912838/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com