在javascript中使用for循环创建一个异步获取序列
create a sequence of asynchronous fetches with for loop in javascript
我有一些JSON格式的文件,它们的名字是这样的:
chapter1。json, chapter2。json,第三章。Json,…
我想在javascript中获取承诺文件的内容,并在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';
});
});
的故事。json是:
{
"heading": "<h1>A story about something</h1>",
"chapterUrls": [
"chapter-1.json",
"chapter-2.json",
"chapter-3.json",
"chapter-4.json",
"chapter-5.json"
]
}
此代码首先并行获取所有章节,然后按顺序显示。
相关文章:
- 将其中一个异步方法重写为使用promise的方法
- Meteor:如何遍历一个数组,这是一个异步方法的结果
- 如何将异步方法返回的值发送到javascript中的另一个异步方法
- 在执行另一个异步函数之前,只有当条件为true时,才执行某些异步函数的最佳方法
- 等待上一个异步函数完成
- node.js:将一个异步函数列表应用于列表列表中的每一项
- 等待一个异步函数在Node.js中返回
- 另一个异步循环中的Javascript异步循环
- 如何在另一个异步`each`方法(NodeJS)内部进行异步方法调用
- 如何在nodejs中将参数从一个异步函数传递到另一个
- 为什么我不需要在Sails.js控制器函数中调用next,即使它在其主体中有一个(异步的?)数据库查询
- Javascript在另一个异步函数结束时调用函数
- 我如何知道最后一个异步函数何时在ob" for键中返回结果?循环
- 如何以组的方式调用一个异步函数?
- 确保两个函数一个接一个地执行,其中第一个函数内部有一个异步调用
- JS磁带-等待前一个异步测试完成,以移动到下一个测试
- 在javascript中使用for循环创建一个异步获取序列
- 如何用Meteor创建一个异步RESTful接口
- dispatchEvent是一个同步函数还是一个异步函数?
- 在Firebase节点客户端中,是一个异步函数