无法将Fetch调用的结果设置为变量,并且Promise无法解析

问题描述 投票:2回答:1

我过去有使用Java进行Promises和Fetch调用的经验,但是我似乎无法弄清楚。

我正在尝试从站点获取数据并存储标题的一部分,如下所示:



async function getData() {

    let response = await fetch("url.....", requestOptions);

    let data = await response.headers.get('set-cookie') 

    return data;
  }

async function main() 
{
    const dataset = await getData();
    console.log(dataset) // This here prints out the data AFTER everything has ran, makes sense as it probably waits for the promise to be resolved.
    data = dataset // This does not set the value of data to dataset. It sets it to Promise <Pending> 
  }

main();


所以从这里最终如何将变量Data设置为已解析的Prom?我认为'await getData()'将在继续执行之前等待对诺言的解析,从而允许将数据设置为实际值而不是诺言。

javascript api promise async-await fetch
1个回答
0
投票

[response.headers.get('set-cookie')不返回承诺,因此您不需要等待。

async function getData() {

    let response = await fetch("url.....", requestOptions);

    let data = response.headers.get('set-cookie') 

    return data;
  }

async function main() 
{
    const dataset = await getData();
    console.log(dataset) // This here prints out the data AFTER everything has ran, makes sense as it probably waits for the promise to be resolved.
    data = dataset // This does not set the value of data to dataset. It sets it to Promise <Pending> 
  }

main();
© www.soinside.com 2019 - 2024. All rights reserved.