大家好,
我想請問大家有辦法用一個變數去接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()
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))
我想這樣就是不懂 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
  })