函數式編程
2021-06-27 13:59:24
我正在努力理解如何在 Javascript 中獲取承諾的值,以便能夠檢查它是真還是假。let valid = validateForm();if ( valid === true ) {}如果我 console.log 有效變量,它返回以下內容:Promise {<pending>}__proto__: Promise[[PromiseStatus]]: "resolved"[[PromiseValue]]: true 在我的 if 語句中,我試圖檢查 promise 值是否為真,但是我不知道如何訪問它:/ 誰能建議如何檢查這個?謝謝
3 回答

PIPIONE
TA貢獻1829條經驗 獲得超9個贊
您可以使用.then或獲得它await。
let valid = validateForm();
valid.then(function(valid) {
if (valid) {
}
})
async function submit () {
const valid = await validateForm();
if (valid) {
}
}
``

qq_笑_17
TA貢獻1818條經驗 獲得超7個贊
使用then或await:
function promiseExample (){
return new Promise((resolve, reject)=> resolve("hello world"))
}
(async () => {
//with then
promiseExample()
.then(data => console.log('with then: ', data))
//with await
var data = await promiseExample()
console.log('with await: ', data);
})()

德瑪西亞99
TA貢獻1770條經驗 獲得超3個贊
很難相信一個簡單的谷歌搜索沒有給你答案,但這里有:
validateForm().then(value => console.log(value))
或者,在異步函數中:
let value = await validateForm();
添加回答
舉報
0/150
提交
取消