这是我第一次使用 API,所以请多多包涵。我正在使用节点应用程序尝试从 API 中获取一些琐事问题。当我尝试运行这个函数时,它所做的只是返回未定义。我知道该变量不应该是未定义的,因为当我console.log(`${result.question}`)在地图循环中运行时它工作正常。这是一段一直搞砸的代码:
var MappedArray;
const fetch = require('node-fetch');
const url = 'https://opentdb.com/api.php?amount=1&type=multiple&difficulty=medium';
function generatequestion(mode)
{
fetch(url)
.then((resp) => resp.json())
.then(function(data) {
let result = data.results; // Get the results
MappedArray = result.map(function(result) { // Map through the results and for each run the code below
switch (mode)
{
case 1:
return `${result.question}`;
break;
case 2:
return `${result.correct_answer}`;
break;
case 3:
return `${result.incorrect_answers}`;
break;
}
})
})
.catch(function(error) {
console.log(error);
});
}
console.log(generatequestion(1));
如果你能帮助我,我提前非常感谢!
牧羊人nacy
慕标5832272
相关分类