如何从 API 响应中访问特定数据

这是我第一次使用 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));


如果你能帮助我,我提前非常感谢!


慕田峪4524236
浏览 173回答 2
2回答

牧羊人nacy

如果您了解更多关于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);})();

慕标5832272

循环后您没有返回 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));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript