JS Promise: calling a function that has a return statement inside resolve

I have a function responsible for uploading images to remote storage.

I also have another function that creates a user in a DB. During the user creation, I should upload the image, get back the URL of the uploaded image, and add it to the user object before adding it to the database. However, I am stuck at getting back the urls:

My function that uploads images:

export const writePicture = (picture) => {
    if (picture !== undefined) {

       //code to upload image to database (...)

                .then((url) => {
                    console.log(`finished executing writePicture, url: ${url}`) //all good here, url is console logged.
                    return url;
                });
        });
    } else {
        console.log("finished executing writePicture")
        return ""
    };
}

The above function is exported to another file where I use promises. My promises are currently set as follows:

//pictureLogo and pictureImage are existing image objects

const waitForLogoUrl = new Promise((resolve, reject) => {
  resolve(writePicture(pictureLogo));
});

const waitForImageUrl = new Promise((resolve, reject) => {
  resolve(writePicture(pictureImage));
});

Promise.all([waitForLogoUrl, waitForImageUrl]).then((urls) => {
  //urls should be an array containing the urls from first and second promise
  console.log("the urls are:");
  console.log(urls);
});

The above is not working as expected. Inside urls, I am getting an array of two undefined entries instead of the two obtained urls.

writePicture() is working fine, it is uploading the pictures and console logging the urls. However the urls are being console logged after the Promise.all has finished:

https://imgur.com/lvP7rrg

I am new to using promises so I am probably missing something about how to call a function inside a resolve. Any help is appreciated.

141 thoughts on “JS Promise: calling a function that has a return statement inside resolve”

Leave a Comment