Javascript 当JS承诺被链接时,如何使用它?

Javascript 当JS承诺被链接时,如何使用它?,javascript,promise,fetch,Javascript,Promise,Fetch,在下面的代码中,为什么我在最后一行得到一个未定义的?如何写入以获取变量a中的响应 function getData(){ const url = "https://jsonplaceholder.typicode.com/users"; url2='https://jsonplaceholder.typicode.com/posts/' fetch(url).then((res) =>{ res.json().then((dataAsJson) => {

在下面的代码中,为什么我在最后一行得到一个未定义的?如何写入以获取变量a中的响应

function getData(){
const url = "https://jsonplaceholder.typicode.com/users";
url2='https://jsonplaceholder.typicode.com/posts/'
fetch(url).then((res) =>{
  res.json().then((dataAsJson) => {
    return(dataAsJson[0].id);
  })
  .then((id)=>{
     fetch(url2+"/"+id).then((res)=> {
     return res.json().then((data) => {
      return(data);
    })
    })
})

})
}


var a = getData();
console.log(a)```

您缺少两个实际将值从一个承诺传递到下一个承诺的返回语句。因此,要使代码正常工作,您必须包括:

异步函数getData(){ 常量url=”https://jsonplaceholder.typicode.com/users"; url2=https://jsonplaceholder.typicode.com/posts/' 常量数据=等待获取(url)。然后((res)=>{ 返回res.json()。然后((dataAsJson)=>{ 返回(dataAsJson[0].id); }) 。然后((id)=>{ 返回fetch(url2+“/”+id)。然后((res)=>{ 返回res.json()。然后((数据)=>{ 返回(数据); }) }) }) }) } 这里还有一个提示:当从一个承诺返回时,不管它是另一个承诺还是一个简单的值-下一个
调用将始终获得未包装的值。所以你实际上不必把所有的承诺电话都放在一起。如果您这样说,它的可读性会更好:

consturl=”https://jsonplaceholder.typicode.com/users";
url2=https://jsonplaceholder.typicode.com/posts/'
常量数据=等待获取(url)
.then((res)=>{return res.json()})
.then((dataAsJson)=>{return(dataAsJson[0].id);})
.then((id)=>{返回获取(url2+“/”+id);})
.then((res)=>{return res.json();})
另外:由于您在每个回调中只返回一个值,因此可以使用JavaScript箭头函数功能,如果只有一个表达式,则该函数会自动返回,并将其进一步简化为:

consturl='1〕https://jsonplaceholder.typicode.com/users';
url2=https://jsonplaceholder.typicode.com/posts/';
常量数据=等待获取(url)
.then(res=>res.json())
.then(dataAsJson=>dataAsJson[0].id)
。然后(id=>fetch(`${url2}/${id}`)
。然后(res=>res.json());
可读性更好,错误更容易发现。:)


更新:我完全忽略了在您的代码中,您试图从异步
getData()
函数同步读取数据@幽灵在他的回答中澄清了这一点——所以这应该是可以接受的答案。但是,为了不让错误的代码存在,我在回答中编辑了正确的行为。

您应该能够使用
wait
简化该功能。 它消除了嵌套回调的需要。这段代码没有经过测试,但在理论上应该可以工作

async function getData() {
  const url = "https://jsonplaceholder.typicode.com/users";
  const url2 = "https://jsonplaceholder.typicode.com/posts/";

  const firstFetch = await fetch(url)
  const firstResult = await firstFetch.json();

  const id = firstResult[0].id;

  const secondFetch = await fetch(url2 + "/" + id)
  return await secondFetch.json();
}


您也可以创建一个新的承诺,以便在第二次获取中解析。但是这种方法比较混乱,因为您没有从
getData()
返回任何内容,您正在得到未定义的内容

承诺及其链接方法,
then()
catch
将返回承诺本身的实例,而不是从
then()
中的回调返回的数据

要获得您期望的行为,一种方法是使用
async
wait
。背着大卫,你会做:

consturl='1〕https://jsonplaceholder.typicode.com/users';
常量url2=https://jsonplaceholder.typicode.com/posts/';
常量数据=等待获取(url)
.then(res=>res.json())
.then(dataAsJson=>dataAsJson[0].id)
。然后(id=>fetch(`${url2}/${id}`)
。然后(res=>res.json());

控制台日志(数据)这是否回答了您的问题?[我试着用这个…但它在等待承诺时返回我..我该如何处理这个问题?是的,我监督了这个问题。谢谢你澄清它-这应该是公认的答案!