我正在查看在medim 上发布的示例。 https://medium.com/software-development-turkey/using-async-await-with-axios-edf8a0fed4b1。我正在努力学习更好的错误处理。 try/catch 似乎是使用 async/await 处理错误的方法。第二个函数依赖于从第一个函数返回的 id。但是在这种情况下,您将如何使用 try/catch?
let sendData = async() => {
let somePhotos = this.somePhotos
let sendInfo = await axios.post("https://yourapihere.com/path", {
yourName: "Mehmet",
yourAge: 29,
yourTitle: "Software Developer"
})
let id = sendInfo.data
let sendPhotos = await axios.post("https://yoursecondapihere.com/path", {
id: id,
photos: somePhotos
})
}
我假设这是对整个事情使用 try/catch 的正确方法。但是如果你想通知第一篇文章出错了怎么办?
let sendData = async() => {
let somePhotos = this.somePhotos
try {
let sendInfo = await axios.post("https://yourapihere.com/path", {
yourName: "Mehmet",
yourAge: 29,
yourTitle: "Software Developer"
})
let id = sendInfo.data
let sendPhotos = await axios.post("https://yoursecondapihere.com/path", {
id: id,
photos: somePhotos
})
} catch (error) {
console.error(error);
}
}
这是正确的吗?这会停止要执行的第二个函数吗? 让 sendData = async() => { 让 somePhotos = this.somePhotos
try {
let sendInfo = await axios.post("https://yourapihere.com/path", {
yourName: "Mehmet",
yourAge: 29,
yourTitle: "Software Developer"
})
if (!sendInfo ) {
throw 'Failed sendInfo';
}
let id = sendInfo.data
let sendPhotos = await axios.post("https://yoursecondapihere.com/path", {
id: id,
photos: somePhotos
})
} catch (error) {
console.error(error);
}
}