簡體   English   中英

從 async/await function with.then 中提取數據

[英]Extract data from async/await function with .then

我對 JS 很陌生,我在從異步/等待 function 中提取數據時遇到問題。 以下確實有效,它會在控制台打印正確的答案,這是一個數字。

fetchData = userData.getPom().then(res => { console.log(res) })

但是,當我嘗試提取 function 的 scope 之外的資源時,它不起作用,它仍然將點打印為 0。

var points = 0
fetchData = userData.getPom().then(res => { points += res })
console.log(points)

我究竟做錯了什么? 提前致謝

兩個 console.logs 的打印屏幕:

在此處輸入圖像描述

您需要使用 await 而不是 then

async myfunction () => {     
    var points = 0
    fetchData = await userData.getPom()
    points += fetchData
    console.log(points);
    return points;
}

嘗試這個:

let points = 0
userData.getPom().then(res => points += res).then(points => {
  console.log(points)
  // Continue your logic here...
})

或使用更新的await/async

async function calcPoints() {
  let points = 0
  let res = await userData.getPom()
  points += res
  console.log(points)
  // Continue your logic here...
  
  return points
}

您的問題與異步 JavaScript有關。 在您的原始代碼中,它將立即 console.log(points)而不是等待 then 操作完成。 因此結果將為 0。您可以在其后面放置另一個 then 或使用更新的await 和 async技術。 (當時發明它是為了擺脫不好的可讀性)。 查看有關此主題的一些教程。

then執行回調 function 之前,您正在將points打印到控制台。

執行順序(可能但不保證)為:

  • 創建新的 fetch promise
  • fetch 開始在“后台”運行
  • 打印points的值
  • 在某些時候,獲取完成,我們增加points

在您到達打印points值的行之前,獲取操作可能會也可能不會完成。 如果您得到不確定的結果,這就是原因。

基本上對於您的用例,您需要等到請求完成后再使用/訪問返回值。

有兩種方法可以解決此問題:

回調中的打印點:

fetchData = userData.getPom().then(res => { 
  console.log(res)
})

打印前等待 promise

async function printPoints() {
  const points = await userData.getPom()
  console.log(points)
}
printPoints()

注意第二點,您只能(截至 2021 年中期,不使用可能有點高級的特殊標志或轉譯)在async function 中使用await ,因此我們必須包裝它。

暫無
暫無

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

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