我正在嘗試從我的 react 本機應用程式將檔案上傳到 AWS S3 存盤桶,但我收到此錯誤 -> 可能未處理的承諾拒絕(id:0) 這是代碼:
import { View, Text, StyleSheet, TouchableOpacity } from 'react-native'
import DocumentPicker from 'react-native-document-picker';
import { RNS3 } from 'react-native-aws3';
import Colors from '../constants/Colors';
const Upload = (props) => {
async function openDocumentFile() {
try {
const res = await DocumentPicker.pickSingle({
type: [DocumentPicker.types.allFiles],
});
console.log(
res.uri,
res.name,
res.type,
res.size
);
const file = {
uri: res.uri,
name: res.name,
type: res.type,
}
const options = {
keyPrefix: "uploads/",
bucket: '',
region: 'ap-south-1',
accessKey: '',
secretKey: '',
successActionStatus: 201
}
RNS3.put(file, options)
.then(response => {
if (response.status !== 201){
console.log(response.status);
throw new Error("Failed to upload image to S3");
}
console.log(response.body);
});
}
catch (err) {
if(DocumentPicker.isCancel(err)) {
console.log("user cancelled");
}
throw err;
}
}
return (
<View style={styles.view}>
<TouchableOpacity style={styles.button} onPress={openDocumentFile}>
<Text style={styles.text}>Upload Documents</Text>
</TouchableOpacity>
</View>
)
}
export default Upload;
const styles = StyleSheet.create({
view: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
button: {
justifyContent: 'center',
alignItems: 'center',
color: Colors.white,
padding: 10,
borderColor: Colors.primary,
borderWidth: 1,
},
text: {
color: Colors.primary,
}
})
這是我得到的輸出,表明檔案已正確選擇,但將檔案上傳到 AWS-S3 的代碼中有錯誤:
LOG content://com.android.providers.downloads.documents/document/msf:31 helloWorld.jpeg image/jpeg 26150
LOG 400
WARN Possible Unhandled Promise Rejection (id: 0):
Error: Failed to upload image to S3
我檢查了其他問題和答案,但沒有找到解決方案。我該如何解決這個錯誤?
uj5u.com熱心網友回復:
你用try/包圍有問題的代碼catch,這很好 - 但是你重新拋出錯誤:
catch (err) {
if(DocumentPicker.isCancel(err)) {
console.log("user cancelled");
}
throw err;
}
這將導致未處理的拒絕,除非有另一個 try/catch或.catch周圍。
只有在呼叫堆疊上有更高的東西可以處理它時才拋出。在這種情況下,沒有 -openDocumentFile應該自己處理所有事情 - 所以不要重新拋出,以防萬一出現問題。
catch (err) {
if(DocumentPicker.isCancel(err)) {
console.log("user cancelled");
}
}
您還需要正確await呼叫RNS3.put- 現在,它沒有被等待,所以它沒有與try/連接catch。這:
RNS3.put(file, options)
.then(response => {
if (response.status !== 201){
console.log(response.status);
throw new Error("Failed to upload image to S3");
}
console.log(response.body);
});
應該
const response = await RNS3.put(file, options)
if (response.status !== 201){
console.log(response.status);
throw new Error("Failed to upload image to S3");
}
console.log(response.body);
一般來說,不要混用await,.then除非你完全理解 Promises 并且知道你在做什么 - 否則,為了避免混淆你自己,我建議在特定的代碼段中只使用一個或另一個。要么await(和try/ catch),要么使用.then,但不能同時在異步邏輯的同一部分中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/431199.html
標籤:javascript 反应式 亚马逊-s3 承诺
上一篇:Kinesis:一個Webhook出現“呼叫PutRecord操作時出現(ValidationException)”錯誤。然而另一個Webhook成功了
