2 回答

TA贡献1862条经验 获得超7个赞
如果您了解更多关于callback, Promise和async/await
您无法在函数之外获取数据的原因console.log()是没有等待generatequestion完成执行。
如果您将 fetch 调用包装在如下所示的 Promise 中,那就太好了。
var MappedArray;
const fetch = require('node-fetch');
const url = 'https://opentdb.com/api.php?amount=1&type=multiple&difficulty=medium';
function generatequestion(mode) {
return new Promise((resolve, reject) => {
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}`;
case 2:
return `${result.correct_answer}`;
case 3:
return `${result.incorrect_answers}`;
}
});
resolve(MappedArray);
})
.catch(function(error) {
console.log(error);
reject(error);
});
});
}
(async () => {
let resp = await generatequestion(1);
console.log(resp);
})();

TA贡献1966条经验 获得超4个赞
循环后您没有返回 MappedArray。
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;
}
})
return MappedArray;
})
.catch(function(error) {
console.log(error);
});
}
console.log(generatequestion(1));
添加回答
举报