我試圖回傳一個承諾是一個 javascript 檔案。但是,有一個奇怪的問題。因此,當我控制臺記錄函式中的回傳值時,它顯示以下內容:
const id = getAccounts()
.then(res => res.find(acc => acc.type === ACCOUNT_TYPES.STARTER))
.then((res) => { return res.id });
console.log(id.then(res => res))

有什么我想念的嗎?一整天都在處理這個問題和研究。如果有人可以提供幫助,我將不勝感激!
更新部分:
const initialState = {
currentAccountId: id.then((res) => { return res; }) || ''
};
uj5u.com熱心網友回復:
呼叫 Promise 的回傳值.then總是另一個 Promise。通過設定currentAccountId為id.then,它將始終是一個 Promise。
你需要this.setState從 Promise 的 resolve 函式內部呼叫:
componentDidMount() {
getAccounts()
.then(res => res.find(acc => acc.type === ACCOUNT_TYPES.STARTER))
.then((res) => { this.setState({ currentAccountId: res }); });
}
就像 React 檔案建議的那樣,使用componentDidMount來啟動異步請求。“如果您需要從遠程端點加載資料,這是一個實體化網路請求的好地方。”
原始答案
id.then將始終回傳一個新的 Promise,這就是您要記錄的內容。要記錄實際值,您可以console.log在 resolve 函式內部移動:
id.then(res => console.log(res))
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/414257.html
標籤:
