[英]Why does Axios (with async/await) return a full promise?
I have a problem with async
/ await
.我有
async
/ await
问题。 Here is my code:这是我的代码:
import axios from 'axios' export default async function getRequestedData (requestAddress, params) { return await axios.get(requestAddress, {params: params}) }
But instead of the result it returns a full promise, so the data is heavily nested inside a promise:但是它返回一个完整的承诺而不是结果,所以数据大量嵌套在一个承诺中:
Like Ha Ja said, I think you still need to resolve the promise.就像 Ha Ja 说的,我认为你仍然需要解决这个承诺。 If you just return the await you're going to get a promise.
如果你只是返回 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
You have to return the data:您必须返回数据:
const response = await axios.get(requestAddress, {params: params})
return response.data;
一个班轮:
return (await axios.get(url)).data;
In React component you can do with this trick:在 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.