簡體   English   中英

為什么我不能在提取 API function 中使用推送的 History.state 屬性集?

[英]Why can't I use pushed History.state property set in a fetch API function?

我使用 fetch() function 編寫了一個 function 調用 API,然后使用 history.pushState(json) 將收到的 json 推送到 History.state。 之后我需要使用 state 屬性,但是當我在 function 之后測試 console.log(history.state) 時,它打印了 null

我嘗試了什么:

function1();
function2();

function function1() {
  const request = new Request('https://reqres.in/api/users?page=2');
  fetch(request)
  .then(response => response.json())
  .then(
    json => 
    {
      history.pushState(json,'','');
      console.log(history.state)
    }
  );
}

function function2() {
  console.log(history.state);
}

我什至嘗試使用 while 循環等待 util history.state 而不是 null(因為我認為這可能是順序問題),但它沒有用。 我想打印出我之前推送到 history.state 的內容,這就是實際結果:

null
// [object Object] 
{
  "page": 2,
  "per_page": 6,
  "total": 12,
...

這是 codepen 上的問題演示: https://codepen.io/L-Ph-t-the-scripter/pen/PoaeqzJ

歡迎來到 Stackoverflow!

function1使用 promises,所以function2被提前調用。 嘗試將function2放在history.pushState調用之后。

function1();

function function1() {
  const request = new Request('https://reqres.in/api/users?page=2');
  fetch(request)
  .then(response => response.json())
  .then(
    json => 
    {
      history.pushState(json,'','');
      function2();
      console.log(history.state)
    }
  );
}

function function2() {
  console.log(history.state);
}

基本上, .then等待它(請求)完成但在等待時繼續運行其他代碼,使function2function1完成之前運行。

我會推薦閱讀這個這個 祝你好運!

您遇到問題是因為 function1 是異步的。 所以你應該等待它的響應,然后運行 function2。

為此,您有 2 個選擇。 首先是像這樣使用 async/await function:

function async runFunctions() {
  await function1();
  function2();
}

runFunctions();

function async function1() {
  const request = new Request('https://reqres.in/api/users?page=2');
  await fetch(request)
  .then(response => response.json())
  .then(
    json => 
    {
      history.pushState(json,'','');
      console.log(history.state)
    }
  );
}

function function2() {
  console.log(history.state);
}

第二種方法是在得到 function1 響應后調用 function2:

function1();

function async function1() {
  const request = new Request('https://reqres.in/api/users?page=2');
  fetch(request)
  .then(response => response.json())
  .then(
    json => 
    {
      history.pushState(json,'','');
      console.log(history.state);
      function2();
    }
  );
}

function function2() {
  console.log(history.state);
}

此處閱讀有關異步/等待的更多信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM