我正在尝试在response => {}
中使用await调用
但是我在等待中得到一个错误,提示期待新行或分号。
我认为该错误是由于函数的结构引起的,但是我不确定如何纠正它。
我要执行的操作是添加/更新用户的个人资料图像。当用户单击touchableOpacity缩略图时,将调用_pickImageHandler()
,如果选择了图像并且响应正常,
它将等待调用uploadImageToStorage
函数,该函数会将图像上传到Firebase Storage。
如果uploadImageToStorage
返回true,那么我想调用editProfileImage将downloadUrl添加到用户文档中。
_pickImageHandler = async () => {
ImagePicker.showImagePicker({title: "Select Image", maxWidth: 800, maxHeight: 600},
// I'm assuming I have to somehow adapt the below response line to fix my problem
response => {
if (response.didCancel) {
console.log("User cancelled!");
if (!response.uri) {
this.showToast('User profile image cannot be empty', 'ok', 'warning')
}
}
else if (response.error) {
//todo look at putting below line into toast message
console.log("Error", response.error);
}
else {
console.log("pickedImage URI: ", response.uri);
console.log("pickedImage FileName: ", response.fileName);
this.setState({
//pickedImageUri: response.uri,
userProfileImageUrl: response.uri,
imageName: response.fileName
});
// Im getting the error on the below line
// Expecting a new line or semicolon
let didImageUploadToStorage = await this._uploadImageToStorage(response.uri, response.fileName);
if (didImageUploadToStorage) {
console.log('didImageUploadToStorage', didImageUploadToStorage);
this.editUserProfileImage()
}
else {
console.log('didImageUploadToStorage', didImageUploadToStorage);
}
}
})
};
_uploadImageToStorage = async (uri, fileName) => {
console.log("uploadImage Triggered!");
console.log("uri: ", uri);
console.log("fileName: ", fileName);
//todo add in another folder after userEvents so it will be userEvents/eventDoc.id/filename
const storageRef = firebase.storage().ref(ref);
await storageRef.put(uri)
.then(snapshot => {
console.log("Upload Success!!!!! :) ");
console.log("downloadUrl: ", snapshot.downloadURL);
this.setState({
userProfileImageUrl: snapshot.downloadURL,
});
return true
})
.catch((error) => {
console.log('FirebaseStorage upload error:', error);
return false
});
};
editUserProfileImage = () => {
console.log('editUserProfileImage FIRED!');
console.log('editUserProfileImage text: ', this.state.userProfileImageUrl);
if (!this.state.userProfileImageUrl.length) {
this.showToast('Profile image URL cannot be empty', 'OK', 'danger');
return
}
console.log('3 userDocExists: ', this.state.userDocExists);
if (this.state.userDocExists) {
console.log('docExists == true');
this.updateFieldInDB(usersCollectionRef, 'i4Mefea0wUjHW07jEk0W', 'userProfileImageUrl', this.state.userProfileImageUrl)
}
else {
console.log('docExists == false');
this.setFieldInDB(usersCollectionRef, 'i4Mefea0wUjHW07jEk0W', 'userProfileImageUrl', this.state.userProfileImageUrl)
}
}
有更少的函数调用来实现更好,更高效的方法。 谢谢您的帮助。
答案 0 :(得分:3)
将async
添加到函数中,然后await
将被识别为函数中的有效关键字(假设您使用的是支持异步函数的浏览器或正在进行编译):
async response => {
// ...
}
答案 1 :(得分:0)
要使用await
运算符,必须在async
函数内部使用它。将您的回调更改为类似的内容即可完成工作。
async (response) => {
// your logic
}
答案 2 :(得分:0)
如我所见,您的代码中,回复应为async