I'm wondering if await and .then can be used in the same async function? Here is my function:
uploadImageToImgur: async function (file) {
return new Promise(function(resolve, reject) {
const url = 'https://api.imgur.com/3/image',
reader = new FileReader();
if (file) {
reader.readAsDataURL(file);
}
reader.onloadend = async function () {
let { result } = reader;
try {
const request = await fetch(url, {
method: 'POST',
headers: {
"Authorization": 'my auth',
},
body: result.replace(/^data:image\/(png|jpg|jpeg|gif);base64,/, "")
})
.then((response) => {
response.json()
.then(data => {
resolve(data.data.link)
})
});
} catch (e) {
reject(e);
}
}
});
},
Then I call this function in another one where I save the object to indexedDb with the link i've got from the imgur API.
this.uploadImageToImgur(image)
.then((image) => {
let db = this.dbOpen.result,
tx = db.transaction('EventsStore', 'readwrite'),
store = tx.objectStore('EventsStore');
event = store.put({ title, location, description, summary, date, time, image });
//rest of the code
});
Why did I choose this approach? Because when I used only await keyword (without promise constructor), data was adding to the db before promise was resolved ;/ What was not what I wanted (probably I made a mistake somewhere.. idk).
My question is if the code above is the correct way to do that (it works as intended) or should I refactor it? If so, please tell me how. This question is rather informative for me than related with a specific problem. Thank You.