[英]Why does Axios (with async/await) return a full promise?
就像 Ha Ja 說的,我認為你仍然需要解決這個承諾。 如果你只是返回 await 你會得到一個承諾。
const fs = require ('fs')
function getText () {
return new Promise( (resolve, reject) => {
fs.readFile('./foo.txt', 'utf8', (err, data) => {
if (err) {
reject(err)
}
resolve(data)
})
})
}
async function output () {
try {
let result = await getText()
console.log("inside try: ", result)
return result
}
catch (err){
console.log(err)
}
}
console.log("outside: ", output())
output().then( result => console.log("after then: ", result))
// outside: Promise { <pending> }
// inside try: foo text
// inside try: foo text
// after then: foo text
您必須返回數據:
const response = await axios.get(requestAddress, {params: params})
return response.data;
一個班輪:
return (await axios.get(url)).data;
在 React 組件中,您可以使用以下技巧:
function InitProduct() {
// Get your product from database
var productId = 'abc';
axios.get('/api/products/' + productId).then(response => {
$('.' + productId).text(response.data.ProductTitle);
});
return (<div className={productId}></div>)
}
export class TestNow extends Component {
render() {
return (
<div>
{InitProduct()}
</div>
)
}
}
異步函數將始終將它返回的內容包裝在承諾中,因此您應該使用 then() 方法鏈接調用者,從而解決該承諾,例如: getRequestedData (requestAddress, params).then ( (data) => { ...do某物... });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.