I have an image upload method on my react component that calls a helper method in a separate helpers.js class to handle the actual upload, so that I can re-use that method elsewhere in my application.
The react component calls into the helper method, the helper method does its job of saving the file to the server all good.... but the original method is not waiting for the promise to resolve. I'm sure it is something small I am missing, but I can't see it.
I've read up on all the similar questions here and implemented what I thought would fix it, done a lot of modifications and refactoring, implemented the await syntax in the helper method, backed it out to the promise syntax again etc. but to no avail.
//Calling method from the react component:
async _uploadPicture(e) { try { const pictureUploadResponse = await HelperMethods.uploadPicture(e); if (pictureUploadResponse.success) { //<=======**PUKES HERE** console.log(pictureUploadResponse.pictureFullPath); this.setState({ picture: pictureUploadResponse.picture, pictureFullPath: pictureUploadResponse.pictureFullPath, errorEditMessage: pictureUploadResponse.message, }); console.log(this.state.pictureFullPath); } else { this.setState({ errorEditMessage: pictureUploadResponse.message }); } } catch (err) { // error console.log(err); } }
//the helper method does its job just great... //the console.log(response.message) line gets outputted just fine...the image is on the server as expected.
// Helper class method
static uploadPicture = (e) => { let formData = new FormData(); formData.append('picToUpload', e.target.files[0]); console.log("upload control 1"); try { const settings = { credentials: 'include', method: 'POST', body: formData, }; fetch(envSettings.API_URI(GLOBALS.ENVIRONMENT) + '/utils/uploadpicture', settings) .then(res1 => { return res1.json() }) .then(response => { if (response.success) { console.log("upload control 2"); console.log(response.message); return { success: true, message: response.message, picture: response.imageUrl, pictureFullPath: envSettings.IMAGE_ROOT_URI(GLOBALS.ENVIRONMENT) + response.imageUrl, } } else { return { success: false, message: response.message, } } }).catch(err => { console.log("error uploading image: " + err) return { success: false, message: err, } }); } catch (err) { console.log(err) return { success: false, message: err, } } } But the calling function doesn't wait, and falls into the outer catch block... Why isn't it waiting?
I really appreciate a second set of eyes on this, I am in the forest and can't see the trees. Thank you.