Is returning an unresolved manually created Promise from an async function considered an anti-pattern?
As async functions return promises by default, it is a little strange to build a new Promise and return it from the same async function.
I have two different methods, in the first one, I have doubts as to whether or not I am doing the new Promise constructor anti-pattern. In the other one, I am definitely sure that it is an anti-pattern.
First function:
export default async (uri) => {
const blob = await new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.onload = function () {
resolve(xhr.response);
};
xhr.onerror = function (e) {
reject(new TypeError("Network request failed"));
};
xhr.responseType = "blob";
xhr.open("GET", uri, true);
xhr.send(null);
});
return blob;
};
Second function:
export async function uploadImageToStorage(
imageUri,
storageFolder = "images",
stateObserver = undefined
) {
const blob = await uriToBlob(imageUri);
const imageId = blob._data.blobId;
const storageRef = storage.ref(storageFolder).child(imageId);
return new Promise((resolve, reject) => {
storageRef.put(blob).on(
"state_changed",
stateObserver,
function error(err) {
blob.close();
reject(err);
},
function complete() {
blob.close();
resolve(imageId);
}
);
});
}
Is it considered to be an anti-pattern the first method implementation?
In the second function, as storageRef.put(blob).on() doesn't return a Promise, my api is callback-based, I need to wrap it inside a Promise, resolving in a complete() callback. If I refactor it to:
export async function uploadImageToStorage(
imageUri,
storageFolder = "images",
stateObserver = undefined
) {
const blob = await uriToBlob(imageUri);
const imageId = blob._data.blobId;
const storageRef = storage.ref(storageFolder).child(imageId);
await new Promise((resolve, reject) => {
storageRef.put(blob).on(
"state_changed",
stateObserver,
function error(err) {
blob.close();
reject(err);
},
function complete() {
blob.close();
resolve(imageId);
}
);
});
return imageId;
}
The new implementation would not be considered as an anti-pattern right?
There is nothing wrong with this in either case. You have to return a Promise, but the API you are using is callback-based, so you have to wrap it in a manually created Promise at some point.
However, there's no point awaiting that Promise within your async function if all you're going to do is return the value that it resolved to. In that case you can just return the unresolved Promise directly.
After doing that, if you are no longer using await in the function, you could also remove the async keyword. But I would leave it in as a signal to the casual reader that the return value will be a Promise.