javascript - 当来自异步函数的数组准备好时,寻找运行代码的正确方法
问题描述
我正在为我当前的 ES6 javascript 解决方案寻找最佳实践解决方案。我希望有人能指出我正确的方向。
我现在正在从分页的 REST API 中获取一堆帖子并将它们存储在一个数组中。帖子的获取是异步的,并且会在 DOM 准备好后的一段时间内完成。
提取脚本完成后,它将输出一个数组,其中包含提取的整个帖子列表。当数组可用时,我想循环遍历它。
我在类似的情况下看到,如果阵列准备好,其他人使用计时器检查每一毫秒。我不确定这是否是正确的实施方法。
使用 ES6 javascript 检查异步函数中的数组是否准备好循环的最佳实践是什么?
以下脚本是我用来获取帖子的脚本。我试图在评论中解释代码。
// Constant variable with the assigned value of a joined string containing the base URL structure of the REST API request.
const apiUrl = websiteUrl + '/wp-json/wp/v2/punkt/';
// Logging out the base URL of the REST API.
console.log('REST API is this: ' + apiUrl);
// Local variable with the default value of true assigned. Variable is used to control the paginated fetch of the API.
let keepfetchingPosts = true;
// Local variable that contains the limit of posts per request.
let limitPerPage = 20;
// Constant variable, which is assigned a function as the value. The function is async and will return a promise.
// The function takes one argument. The argument holds the value of the page number.
const getPosts = async function(pageNo = 1) {
// Local variable assigned with the base URL string of the REST API request. Additional queries are added to the end of the string.
let requestUrl = apiUrl + `?page=${pageNo}&per_page=${limitPerPage}`;
// Logging out the REST API request
console.log('URL is this: ' + requestUrl);
// Logging out the argument 'pageNo'
console.log('Retreiving data from API for page : ' + pageNo);
// Local variable assigned with a fetch function that returns a promise. The URL request are used as the function argument.
let apiResults = await fetch(requestUrl)
// If request is success, then log and return the following to the local variable.
.then(function(response){
// Logging out the status code of the response.
console.log('HTTP response is: ' + response.status);
// return JSON and status code of the XHR request
return {
data: response.json(),
status: response.status
}
})
// Catch the error and log it out within the console.
.catch(function(error){
console.log('HTTP response is: ' + error.status)
});
// If the length of the request is less than the limitPerPage variable and status code is 200, then...
if (apiResults.length < limitPerPage && apiResults.status === 200){
// Set the boolean to false
keepfetchingPosts = false;
// Return the JSON of the successfull response.
return apiResults.data;
} else if (apiResults.status === 200) {
// If the status code is 200, then return the JSON of the successfull response
return apiResults.data;
} else {
// Otherwise, set the boolean to false
keepfetchingPosts = false;
}
}
// Defining a constant variable that holds and async fynction. An async functon will always return a promise.
// The function takes one argument, which is set to 1 by default.
const getEntirePostList = async function(pageNo = 1) {
// Try and catch statement used to handle the errors that might occur.
try {
// Constant variable which is set to the return variable of the function getPost(). Get post returns the successfull paginated response of the request.
const results = await getPosts(pageNo);
// Logging out a string including the length of the array.
console.log('Current array contain ' + results.length + ' items...');
// Conditional statement that checks if the length of the array named 'results' is less than the variable named limitPerPage. Condition is also checked, if bolean is true.
// If the conditions are met, the code will join the arrays into one big array.
if (results.length < limitPerPage && keepfetchingPosts === true) {
// Logging out a string that indicates an attempt to combine that last array to the existing array.
console.log('Combining last array!');
// Return the combined array.
return results;
} else if (keepfetchingPosts === true) {
// Logging out a string that indicates an attempt to combine the recent fetched array to the existing array.
console.log('Combining arrays!');
// Returning the new combined array and increments the pageNo variable with 1.
return results.concat(await getEntirePostList(pageNo+1));
} else {
// Logging out a string that indicates the script will stop fetching more posts from the REST API.
console.log('Stop fetching posts and return results');
// Returning the complete array.
return results;
}
// Catch statement that takes the argument of the error that occured.
} catch(error) {
// Logging out the error.
console.log(error);
}
};( async () => {
// Constant variable with the assigned value received from the function
const entireList = await getEntirePostList();
// Logging out the enite list of results collected from the REST API
console.log(entireList);
})
();
该脚本吐出名为“entireList”的数组。
解决方案
推荐阅读
- c# - CFind 在研究级别失败 - 不支持 SOP 类或没有为抽象语法找到可接受的表示上下文
- node.js - 如何将 NPM 可执行文件上传到 nexus 服务器
- interpolation - terraform 更改远程执行的计数索引行为
- docker - 如何知道 Docker ENTRYPOINT 是否完成执行
- powerquery - Power Query 中的随机数与查询折叠
- .htaccess - htaccess 将所有以 .html 结尾的页面重定向到不带 html 的页面 除了某些页面
- api - 调用 API 时如何在 Postman 上提供用户名和密码
- ios - 将 Double 转换为 CLLocationDegrees [SWIFT]
- ios - React cli 无法在设备上运行应用程序,但从 Xcode 运行
- java - Java 流 ifPresent orElse /orElseGet