I have a method that creates an order folder first, then creates multiple product subfolders in that order folder. And to each product folder, I move some images. I want all this to be done before the method returns true. I have wrote the following code but it not working as i expected.
The for loop stucks at await movefile and function does not execute further. I'm using async/await
for the first time and have no idea why its happening. Can anyone please point out what I'm doing wrong or can it be done in a better way?
static async saveOrderPhotos(allProduct , transactionId) {
var products = allProduct;
var orderTransactionId = transactionId;
var success = true;
const makedir = promisify(fs.mkdir);
const movefile = promisify(fsExtra.move);
const movefiles = async (i) => {
for (let j = 0; j < products[i].photos.length; j++) {
await movefile(`public/uploads/orders/temporary/${Order.getfilename(products[i].photos[j])}`, `public/uploads/orders/${products[i].photos[j]}`, (err) => {
});
}
console.log("Files moves for product-" , i+1);
return true;
}
const createProductFolders = async () => {
for (let i = 0; i < products.length; i++) {
if (products[i].photos.length > 0) {
await makedir(`public/uploads/orders/Order-${orderTransactionId}/Product-${i + 1}`, async () => {
console.log("Product Directory Created");
// then move files into the product folder
await movefiles(i);
});
}
}
return true;
}
try {
if (Order.hasPhotos(products)) {
// create order folder
await makedir(`public/uploads/orders/Order-${orderTransactionId}`, async () => {
console.log("Order Directory Created");
// then create product folder
await createProductFolders();
console.log("All Files moved");
});
}
console.log("Returning true");
return true;
} catch (err) {
console.log(err);
}
}
Do not pass a callback to movefile()
and makedir()
as the last argument. These are already promisified versions of the functions so the callback is used by that. They communicate back completion via their returned promise, not via a callback.
When you pass a callback, it screws up the arguments to the promisified version and the promise never gets its callback called so the promise never resolves and the code gets stuck.
Note, current versions of nodejs already have promisified versions of a bunch of functions. For example, you can directly use these that might be relevant to your code:
fs.promises.mkdir()
fs.promises.rename()
fs.promises.copyFile()