Your code has one Promise
who has another Promise
within a function resolve
of the first Promise
, and none of this is necessary, because, the axios
already returns a Promise
and can be solved easily:
async function pegaDados() {
try {
return await axios
.get('https://cd8wxyy7ba.execute-api.sa-east-1.amazonaws.com/dev/products');
} catch (e) {
console.log(e);
}
}
is one of the forms of solution with async/await
where this function returns the information of this API
or an error where it can be checked.
Functional example with React using then
, because here on the site does not work unfortunately async/await
, but, nothing prevents use, example:
function App() {
const [data, setData] = React.useState([]);
const loadData = () => {
axios.get('https://cd8wxyy7ba.execute-api.sa-east-1.amazonaws.com/dev/products')
.then(result => setData(result.data));
}
React.useEffect(() => {
loadData();
}, []);
if (data.length === 0) {
return <div>Carregando ...</div>;
}
return (
<React.Fragment>
{data.map(item => (
<div>
{item.productSku} - {item.productDescription}
</div>
))}
</React.Fragment>
)
}
ReactDOM.render( <App/> , document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<div id="root"></div>
It is because it is usually not possible to return data from within a then, what you can do is to place this chunk within an async function and return with await: type:
function teste async () { const dados = await pegaDados();
– adventistaam
É porque geralmente não se é possível retornar dados de dentro de um then
wrong statement!– novic