0

I have two async functions:

  • uploadImage: uploads an image to Firebase storage and returns the URL
  • postItem: posts an item to Firebase DB and needs the URL from the uploaded image, whichs is returned from the uploadImage function.

When the submitHandler function is called, both uploadImage and postItem are executed, and I pass the result from uploadImage as an argument to postItem. However the value from resUpload is undefined right now.

My Question

How do I wait for uploadImage to finish executing so I can pass the imageURL as an argument to the postItem function,

const uploadImage = async () => {
    let imageURL;
    uploadBytes(imageRef, image)
      .then((snapshot) => {
        return getDownloadURL(snapshot.ref);
      })
      .then((downloadURL) => {
        imageURL = downloadURL;
      });
    return imageURL;
};

const postItem = async (URL: string) => {
    // sends POST request using data from URL arg
    const response = await fetch('https://foo');
    const data = await response.json();
};

const submitHandler = async () => {
    const resUpload = await uploadImage();
    //resUpload is undefined
    const resPost = await postItem(resUpload);
};
Bram
  • 669
  • 3
  • 12
  • 25
  • 1
    `uploadImage` is returning `undefined` because it's not internally awaiting the asynchronous operation or returning the Promise for that operation. It declares a variable, invokes an asynchronous operation, then immediately returns that declared variable. The rest of the code is making use of `await`, it would make sense to apply that here as well. – David Oct 14 '22 at 13:51

0 Answers0