为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕田峪4524236 2022-06-05 10:30:08
这是我第一次使用 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));如果你能帮助我,我提前非常感谢!
查看完整描述

2 回答

?
牧羊人nacy

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);

})();


查看完整回答
反对 回复 2022-06-05
?
慕标5832272

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));


查看完整回答
反对 回复 2022-06-05
  • 2 回答
  • 0 关注
  • 128 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号