简体   繁体   English

获取方法在 function 外部有效,但在 function 内部无效

[英]Fetch method works outside a function but doesn't work inside a function

I'm just getting started with javascript so please bear with me.我刚刚开始使用 javascript,所以请多多包涵。 I'm trying to fetch a value from an API but I'm struggling with it.我正在尝试从 API 中获取一个值,但我正在努力解决这个问题。

This "works" as in it prints the name I'm trying to get.这个“有效”,因为它打印了我想要得到的名字。

let nameURL = "/login/userInfo/name?email=" + email;

 fetch(nameURL, { method: "GET" })
  .then((res) => res.json())
  .then((json) => {
    console.log(json[0])
    
  });

This doesn't work, returns an undefined value:这不起作用,返回一个未定义的值:

let nameURL = "/login/userInfo/name?email=" + email;



function getName() {
    fetch(nameURL, { method: "GET" })
      .then((res) => res.json())
      .then((json) => {
        return json[0]
        
      });
  }
  
  console.log(getName())

What I want to do is use that function to bring out json[0], as I need it to use that information.我想要做的是使用 function 带出 json[0],因为我需要它来使用该信息。

EDIT: since I'm using React, I ended up using the fetch call inside a component and then using hooks to set values.编辑:因为我使用的是 React,所以我最终在组件内部使用了 fetch 调用,然后使用钩子来设置值。

let nameURL = "/login/userInfo/name?email=" + email;

// this is your function: it works fine, except that you need to
// `return fetch`, and you don't need to specify `GET` because
// that's the default
function getName() {
  return fetch(nameURL)
    .then((res) => res.json())
    .then((json) => json[0]);
}

// You need to `.then` it to get the result, 
getName().then((name) => {
  // do other work with `name`
})

As @Alex said you can also do this with the async/await syntax:正如@Alex 所说,您也可以使用async/await语法执行此操作:

async function getName() {
  const res = await fetch(nameURL)
  const json = await res.json()
  return json[0]
}

// somewhere else
getName().then((name) => {});
// or
(async () => {
  const name = await getName()
})();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM