It is generally advised to avoid mixing await
and .then()
in the same function. Instead, it's recommended to choose one style over the other for a particular function. Although the code you provided will function correctly, here are two more consistent ways to write it:
Here is an example without using async/await
:
export function loadSingleArweaveAbstraction(absId : string) : Promise<AbstractionPreview> {
return axios({
method: 'get',
url: ARWEAVE_URL + absId,
responseType: 'json'
}).then(function(response) {
return {
name: response.data.name,
imageUri: response.data.image,
symbol: response.data.symbol,
};
}).catch(function(e) {
console.log(e);
return { name: "Null", imageUri: "null", symbol: "null" };
});
}
And here is an example using async/await
:
export async function loadSingleArweaveAbstraction(absId: string): Promise <AbstractionPreview> {
try {
let response: AbstractionPreview = await axios({
method: 'get',
url: ARWEAVE_URL + absId,
responseType: 'json'
});
return {
name: response.data.name,
imageUri: response.data.image,
symbol: response.data.symbol,
};
} catch (e) {
console.log(e);
return { name: "Null", imageUri: "null", symbol: "null" };
}
}
There isn't necessarily a "right" way between these two options. It ultimately depends on personal preference. I personally find await
easier to read when dealing with multiple asynchronous operations that need to be sequenced, as opposed to chained .then()
handlers. When there is only one asynchronous operation, both methods can be equally simple.
It's important to always log errors that may occur. Failing to do so could lead to issues within your system, where errors are hidden and difficult to detect.
P.S. If there are any TypeScript syntax errors present, please feel free to correct them as I am not well-versed in TypeScript.
In both cases, we are essentially waiting for the asynchronous call to complete before returning. What then is the purpose of making asynchronous calls if they seem to behave synchronously?
Even though these functions appear to operate synchronously due to the use of await
, they actually return a promise immediately when the asynchronous axios()
call is initiated. This allows the caller to execute other tasks while awaiting the completion of these operations. Once the asynchronous task finishes, the functions process the results and resolve the initial promise, notifying the caller of the final outcome. Therefore, this is non-blocking and asynchronous behavior, allowing Nodejs and the caller to handle other events concurrently.
Can an unfulfilled promise be returned?
Yes, both examples already return an unfulfilled promise, which is typically the case when working with promises.