[英]Using Array Method inside ASYNC/AWAIT between API calls in Javascript
I want to make my code more readable, using async/await instead of using fetch(). 我想使用async / await而不是fetch()使代码更具可读性。
My code needs to do the following : 我的代码需要执行以下操作:
The way I did it using fetch() 我使用fetch()的方式
componentDidMount() {
const postsURL = 'https://jsonplaceholder.typicode.com/posts';
fetch(postsURL)
.then(res => res.json())
.then(posts => {
const randomNumber = Math.floor(Math.random() * 100);
const randomPost = posts.find(post => post.id === randomNumber);
fetch(
`https://jsonplaceholder.typicode.com/users/${
randomPost.userId
}`
).then(res => {
res.json().then(user => {
this.setState(() => {
return {
posts: posts,
showingPost: randomPost,
showingUser: user
};
});
});
});
})
.catch(err => console.log(err));
}
Now I'm trying to convert this code altogether into one async function getData() 现在,我尝试将这段代码完全转换为一个异步函数getData()
async getData() {
// get posts
const getPostsResponse = await fetch(
'https://jsonplaceholder.typicode.com/posts'
);
const posts = await getPostsResponse.json();
// get showingPost
const randomPost = posts.find(
post => post.id === Math.floor(Math.random() * 100)
);
//get user
const getUserResponse = await fetch(
`https://jsonplaceholder.typicode.com/users/${randomPost.userId}`
);
const user = await getUserResponse.json();
// return/setState
return this.setState(() => {
return {
posts: posts,
showingPost: randomPost,
showingUser: user
};
});
}
componentDidMount() {
this.getData();
}
The problem is - randomPost
variable in this async function sometimes returns undefined. 问题是-此异步函数中的randomPost
变量有时返回未定义。 It has to be set before moving to the next API call. 必须先进行设置,然后再进行下一个API调用。
How do I properly use find(), or any other method inside async/await function between 2 API calls? 如何在2个API调用之间正确使用find()或async / await函数内的任何其他方法? Thanks! 谢谢!
You change the way you're calling find()
. 您可以更改调用find()
。 In the code that uses async/await
, you're calculating a different random number to test each array element against, but in the original code you just calculate randomNumber
once. 在使用async/await
的代码中,您正在计算一个不同的随机数来测试每个数组元素,但是在原始代码中,您只需计算一次randomNumber
。 The chance of finding a match in the second way is very low. 用第二种方法找到比赛的机会很小。
So do the same thing in the new code. 因此,在新代码中执行相同的操作。
async getData() {
// get posts
const getPostsResponse = await fetch(
'https://jsonplaceholder.typicode.com/posts'
);
const posts = await getPostsResponse.json();
// get showingPost
const randomNumber = Math.floor(Math.random() * 100);
const randomPost = await posts.find(
post => post.id === randomNumber
);
A simpler way to pick a random element of an array is: 选择数组随机元素的一种更简单的方法是:
const randomPost = posts[Math.floor(Math.random() * posts.length)];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.