嗨,我正在制作一个 ReactJS 项目,我正在尝试修改一个函数以使其更具可读性......它有很多 API 调用,所以它有很多 .then(( .catch(( 块。 你有一些建议来避免所有这些 .then(( .catch(( 块吗?因为现在真的是不可读的。
const saveImgAvatar = (img_input) => {
setLoadingUploadImg(true)
//Salvo su aws e creo il cdn
let file = img_input
// Split the filename to get the name and type
let fileParts = img_input.name.split('.');
let fileName = context.currentUser.uid + "-img-avatar";
let fileType = fileParts[1];
console.log("file name" + fileName)
console.log("file parts" + fileType)
axios.post(process.env.REACT_APP_API_URL, {
fileName: fileName,
fileType: fileType
})
.then(response => {
var returnData = response.data.data.returnData;
var signedRequest = returnData.signedRequest;
var url = returnData.url;
//Ora salvo l'url
console.log("Recieved a signed request " + signedRequest);
// Put the fileType in the headers for the upload
var options = {
headers: {
'Content-Type': fileType
}
};
axios.put(signedRequest, file, options)
.then(result => {
setTalentImgAvatar(url)
//setCurrentImgAvatar(returnData.url)
//Salvo sul db
axios.put(process.env.REACT_APP_API_URL, { img_url: url })
.then(res => {
setLoadingUploadImg(false)
toggleShowEditImg(!showEditImg)
setAlertProfConf(true)
setTimeout(() => {
setAlertProfConf(false)
}, 1000)
})
.catch(function (error) {
console.log(error)
notifyMessage("error", "Errore nell'aggiornamento immagine")
setLoadingUploadImg(false)
})
})
.catch(error => {
//Apro un messaggio di errore
notifyMessage("error", "Errore")
//Notificato l'errore fermo lo spinner di loading
setLoadingUploadImg(false)
})
})
.catch(error => {
console.log(JSON.stringify(error));
//Apro un messaggio di errore
notifyMessage("error", "Errore")
//Notificato l'errore fermo lo spinner di loading
setLoadingUploadImg(false)
})
}
尝试使用 asnyc/await。
const saveImgAvatar = async (img_input) => {
setLoadingUploadImg(true)
//Salvo su aws e creo il cdn
let file = img_input
// Split the filename to get the name and type
let fileParts = img_input.name.split('.');
let fileName = context.currentUser.uid + "-img-avatar";
let fileType = fileParts[1];
console.log("file name" + fileName)
console.log("file parts" + fileType)
const response = await axios.post(process.env.REACT_APP_API_URL, {
fileName: fileName,
fileType: fileType
});
var returnData = response.data.data.returnData;
var signedRequest = returnData.signedRequest;
var url = returnData.url;
//Ora salvo l'url
console.log("Recieved a signed request " + signedRequest);
// Put the fileType in the headers for the upload
var options = {
headers: {
'Content-Type': fileType
}
};
const result = await axios.put(signedRequest, file, options);
setTalentImgAvatar(url)
//setCurrentImgAvatar(returnData.url)
//Salvo sul db
const res = axios.put(process.env.REACT_APP_API_URL, { img_url: url });
setLoadingUploadImg(false)
toggleShowEditImg(!showEditImg)
setAlertProfConf(true)
setTimeout(() => {
setAlertProfConf(false)
}, 1000)
})
使用async
/await
的一个主要好处是可以避免回调地狱。
网上有很多很棒的资源可供学习,但你可以使用 async/await 来实现这样的东西:
try {
const res1 = await asyncProcess1(); //Current execution context is suspended until this process is finished
const res2 = await asyncProcess2(res1);
const res3 = await asyncProcess3(res2);
} catch (exception) {
//do something with exception
}
async function asyncProcess1() {
//async task here:
return "done";
}
由于put()
、post()
等返回一个承诺,只需在第一级回调中返回该承诺并在新的顶级then()
中处理响应。来自返回 promise 的解析数据将被传递给链中的下一个then()
回调,例如:
axios.post().then((data)=>{
/*process datat*/
return axios.put();
}).then((postResponseData)=>{
/*process datat*/
return axios.put();
}).then((putResponseData)=>{
/*process datat*/
return axios.post();
}).catch((err)=>{
/*...*/
});
您还可以使用 async/await 语法来提供更同步样式的代码的外观,但需要单独管理捕获:
async function run(){
let resp = await axios.post(...);
/*... process response ...*/
let resp2 = await axios.put();
/*... process the next response ... */
let resp3 = await.post(...);
/* etc etc */
return finalData;
}
run().then((data)=>{ console.log(data); });