iT邦幫忙

0

【JS】要如何取出Async的值

  • 分享至 

  • xImage

大家好,
我想請問大家有辦法用一個變數去接Async的回傳值嗎?

像是這樣:

let response = (async function(){
    let res = await fetch('http://localhost')
    let resJson = await res.json()
    return resJson //假如 resJson = 1
})()

let ans = response + 2

還是有甚麼類似的方法,比較方便使用呢?感謝


謝謝大家的回答,看來方法果然只能這樣

//先設變數,與預設值
let val = 0
//再設定async function
const initialData = async()=>{
    //修改變數
    //修改html
}
//再執行
initialData()
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

0
alien663
iT邦研究生 5 級 ‧ 2022-12-14 16:51:15
最佳解答
let sourceData = []
fetch("https:\\localhost", {
        method: "POST",
        body: JSON.stringify({ "payload": formData }),
        headers: {'Content-Type': 'application/json'}
    }
).then((response) => {return response.json();})
.then((sourceData) => {sourceData = JSON.parse(sourceData)})
.catch(error => console.error('Error:', error))
0
Han
iT邦研究生 1 級 ‧ 2022-12-14 17:51:15

我想這樣就是不懂 async function 回傳的東西
他回傳的是一個 Promise 物件

所以,要嘛你就再弄一個 async function 來處理

async function example() {
  let response = await fetch('http://localhost')
  let responseJson = await response.json()
  let ans = responseJson + 2
  console.log(ans) // 輸出 3
}

不然就是使用 .then 來處理 Promise

let response = fetch('http://localhost')
  .then(response => response.json())
  .then(responseJson => responseJson + 2)
  .then(ans => {
    console.log(ans) // 輸出 3
  })

我要發表回答

立即登入回答