[英]Get value returned from Promise in JavaScript
我是 JavaScript 的新手,對Promise
有點困惑,這就是我所擁有的:
export const testFunction = () => dispatch => {
otherFunction().then(( response ) => {
//do something...
return response;
}).catch(( error ) => {
//do something...
return error;
});
}
在另一個文件中,我試圖獲取從then
返回的值,如下所示:
let result = this.props.testFunction()
像這樣:
let result = this.props.testFunction ().then(( result ) => {
console.log(result);
}).catch(( error ) => {
console.log(result); // undefined
});
但是我得到undefined
的result
,獲得該值的正確方法是什么?
testFunction
沒有返回 Promise 所以你不能使用then
或catch
並返回undefined
因為好吧,它沒有返回任何東西。 嘗試像下面的示例一樣返回 promise 但是我不確定 dispatch 參數應該做什么,所以我已經刪除了它,希望這會有所幫助:
export const testFunction = () => {
return new Promise((resolve, reject) => {
otherFunction().then(( response ) => {
//do something...
resolve(response);
}).catch(( error ) => {
//do something...
reject(error);
});
});
}
當您嘗試返回 promise 以在另一個文件中使用它時,您必須使用以下語法:
const testFunction = () => {
return new Promise((resolve, reject) => {
if (error) {
return reject(error); // this is the value sent to .catch(error)
}
return resolve(valueToReturn); // this is the value sent to .then(result)
});
}
這就是您創建 promise 以在您想要的地方使用的方式,如果它有錯誤,它將發送到 catch 塊,否則您應該看到 console.log(result) 值。
在您的外部文件中,您可以使用您正在使用的語法,以這種方式嘗試查看 console.log 值。
這是查看更多信息的鏈接: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.