There's simply no reason to wrap your existing promise with another promise and no reason to use await
or async
here either:
const getData = function(){
return axios.get(some_data);
}
Wrapping an existing promise with a manually created promise is a promise anti-pattern and should not be done. Instead, you should just return the promise you already have.
If you're going to use more than one async operation and thus find you want to use await
rather than chain your promises with .then()
, then you can do that like this:
const getData = async function(){
let val = await axios.get(some_data);
let otherVal = await someOtherFunction();
return something;
}
Note also that if you want a rejected promise to just get returned as a rejection, you don't have to catch
it locally in an async
function. If you one of the promises you are using await
on rejects, that will just reject the promise that your async
function returns with that error.
If you wanted to catch the error locally and do something about it, then you would use try/catch:
const getData = async function(){
try {
let val = await axios.get(some_data);
let otherVal = await someOtherFunction();
return something;
} catch(e) {
// some something with the error and decide what to return
}
}
async function
as aPromise
executor function! Avoid thePromise
constructor antipattern! \$\endgroup\$ – Bergi Dec 22 '17 at 10:48