2 回答
TA贡献2080条经验 获得超4个赞
好的,所以我改变了一点代码。
async function getRandomWord() {
try {
const res = await fetch('https://randomuser.me/api');
const data = await res.json();
const randomWord = data.results[0].location.country;
return randomWord.toUpperCase();
// words.push(randomWord.toUpperCase());
} catch (e) {
console.log(
'There has been a problem with your fetch operation: ' + e.message
);
}
}
然后刚刚打电话给
(async () => {
selectedWord = await getRandomWord();
displayWord();
})();
不敢相信我做了这个:D谢谢。
TA贡献1873条经验 获得超9个赞
读取尚未解决,并且在执行时尚未填充。使用 Promise.all,然后:words[]selectedWords =
const p = Promise.all([
getRandomWord(),
getRandomWord(),
getRandomWord(),
getRandomWord()
]);
const words = [];
p.then(()=>{
const selectedWord = words[Math.floor(Math.random() * words.length)];
console.log(words);
console.log(selectedWord);
});
// Fetch some random words
async function getRandomWord() {
const res = await fetch('https://randomuser.me/api');
const data = await res.json();
const randomWord = data.results[0].location.country;
words.push(randomWord);
}
注意:如果您不希望快速失败行为,则需要使用 Promise.allSettled,其中任何失败都会导致它立即返回。另请注意,我正在使用Promise.all,以便它将同时运行提取,而不是按顺序等待它们。
异步/等待而不是然后
(async()=>{
let words = [];
for(var i = 0; i < 4; i++)
words.push(getRandomWord());
words = await Promise.all(words);
const selectedWord = words[Math.floor(Math.random() * words.length)];
console.log(words);
console.log(selectedWord);
})()
// Fetch some random words
async function getRandomWord() {
const res = await fetch('https://randomuser.me/api');
const data = await res.json();
const randomWord = data.results[0].location.country;
return randomWord;
}
添加回答
举报