I have a react typescript App, in my App I use IndexedDB for storing some Data. I have separate class for working with IndexedDB call DB . in one of my class methods I use this code for getting all data
public async getAll(){
const promise = await new Promise((resolve,reject)=>{
const req = this.openDB();
req.addEventListener("error", (e) => {
console.log("error ", e);
reject ("error");
});
req.addEventListener("success", () => {
const db = req.result;
const tx = db.transaction("tasks", "readonly");
tx.addEventListener("complete", () => {
console.log("transaction complete");
db.close();
});
const readObj = tx.objectStore("tasks");
const data = readObj.getAll();
data.addEventListener("success",(e)=>{
console.log(data);
console.log(e);
resolve (data.result);
});
});
});
return await promise;
}
and in one of my component event handler
const db = new DB();
const dataPro = db.getAll();
dataPro.then((resData)=>{
console.log(resData); // I have Data I need it
}
but the getAll func works fine without async-await , so my question is : is it really Necessary to use async-await in getAll func ?? I mean is there any situation that I need async-await
I try getAll func code without async-await and it works fine for me
The async
and await
keywords are essentially "syntactic sugar" for working with Promises
in a cleaner way. They're not necessary, but are very often useful. However, if all the function does is create and return a Promise
then there's little use for them.
The usage shown is even already redundant. You're awaiting the same Promise
twice. Once here:
const promise = await new Promise((resolve,reject)=>{
And once here:
return await promise;
And since the function is async
, you still need to await (or follow with a callback) when calling it:
dataPro.then((resData)=>{
As you're observing, this is all very redundant and unneccessary. If the function itself doesn't internally await
anything then it doesn't need to be async
. It can just return the created Promise
:
public getAll(){
return new Promise((resolve,reject)=>{
// the rest of the code in the Promise
});
}
And the usage of the function wouldn't change.
If the vendor provides a Promise-based API then you can use that and the async
and await
keywords can help make the code much simpler and easier to reason about. If they don't then wrapping otherwise asynchronous operations (with callbacks/events/etc.) in a manual Promise
and returning that so consuming code can optionally make use of async
and await
(as you're doing here) is a common pattern.