[英]How can I add async await to this function
export function fetchNews(data) {
const news = []
var numOfArticlesArray = fetchNewsPreprocessing(data)
data.map((interest, index) => {
fetch(`https://newsapi.org/v2/top-headlines?country=us&category=${interest}&apiKey=`)
.then(res => res.json())
.then(res => res.articles)
.then(res => {
for (let i = 0; i < numOfArticlesArray[index]; i++) {
news.push(res[i])
}
})
.catch(err => console.log(err))
})
console.log(news);
}
所以這是函數,我的問題是我得到了這個console.log(news);
在我完成將這里的news.push(res[i])
添加到我的news
數組之前,這會導致一個空白數組。
我嘗試將 async 和 await 添加到這樣的async function fetchNews(data)
和await data.map((interest, index) => {
但沒有用。
提前致謝。
您想串行還是並行執行fetch()
調用?
如果你想串行執行它們,那么這樣的事情將起作用:
export function fetchNews(data) {
const news = [];
const numOfArticlesArray = fetchNewsPreprocessing(data);
data.map( async (interest, index) => {
const url = `https://newsapi.org/v2/top-headlines?country=us&category=${interest}&apiKey=`;
try {
const res = await fetch(url).then(res => res.json());
const articles = res.articles;
for ( let i = 0 ; i < numOfArticlesArray[index] ; i++ ) {
news.push(articles[i]);
}
} catch (err) {
console.log(err);
}
})
console.log(news);
}
但是,如果您想並行執行它們,那么您想要的是這樣的:
export async function fetchNews(data) {
const news = [];
const numOfArticlesArray = fetchNewsPreprocessing(data);
const requests = data.map( (interest, index) => {
const url = `https://newsapi.org/v2/top-headlines?country=us&category=${interest}&apiKey=`;
const res = fetch(url).then(res => res.json());
return res;
})
const responses = await Promise.all( requests );
for ( const i = 0 ; i < responses.length ; ++i ) {
const res = responses[i];
const articles = res.articles;
for ( let j = 0 ; j < numOfArticlesArray[i] ; ++j ) {
news.push(articles[j]);
}
}
console.log(news);
}
你應該把await
放在fetch()
前面。 例如,這段代碼將輸出帶有test
元素的news
數組:
async function fetchNews(data) {
let news = [];
await fetch(url).then(() => news.push('test'));
console.log(news)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.