I'm using igmur api to upload images. I wrote an application in Node.js using Promises, async-await. (please do note that I'm fairly new to these concepts).
My code does seem to work. It uploads images to igmur. But, the issue is, the promise does not get resolved. Please refer the code below.
router.post('/images/upload', async (req, res) => {
/* we would receive a request of file paths as array */
let filePaths = req.body.urls;
let multipleUpload = new Promise(async (resolve, reject) => {
let upload_len = filePaths.length,
upload_res = new Array();
for (let i = 0; i <= upload_len + 1; i++) {
let filePath = filePaths[i];
await imgur.upload(filePath, (error, result) => {
console.log(" A -> ");
if (upload_res.length === upload_len) {
console.log("******");
/* resolve promise after upload is complete */
resolve(upload_res)
} else if (result) {
/*push public_ids in an array */
console.log("OK")
upload_res.push(result.public_id);
} else if (error) {
console.log(error)
reject(error)
}
})
}
})
.then((result) => console.log(result))
.catch((error) => error)
let upload = await multipleUpload;
res.json({
'response': upload
})
})
I followed this tutorial, which does something similar.
I see at least two problems:
imgur.upload
does not return a Promise, as it accepts a callback function.I think this should fix it:
router.post('/images/upload', async (req, res) => {
let filePaths = req.body.urls
let upload_len = filePaths.length
let multipleUpload = filePaths.map(filePath => {
return new Promise((resolve, reject) => {
imgur.upload(filePath, (err, result) => {
if (err) {
reject(err)
} else {
resolve(result.public_id)
}
})
})
})
let upload = await Promise.all(multipleUpload)
res.json({
response: upload,
})
})