【发布时间】:2021-02-12 17:30:16
【问题描述】:
我很困惑。我有一个异步函数,我在其中调用另一个函数,当失败时,错误出现在浏览器控制台中,但主函数继续。
下面这个函数失败了,我在浏览器控制台日志中看到错误:
async function create (newContact) {
try {
const request = await axios.post(baseUrl, newContact);
return request.data;
} catch (error) {
console.log(`Failed to create contact. Error: ${error}`)
}
}
我在下面的另一个函数中调用该函数。发布请求肯定会得到 400 响应错误,但下面此函数中的代码继续没有错误(参见 Else 语句)。为什么?
async function addPerson (event) {
try {
event.preventDefault();
const newPerson = {
name : newName,
number: newNumber
}
const person = searchPeople(newName);
if (person !== -1) {
if (window.confirm(`${newName} is already added to phonebook, replace the old number with a new one?`)) {
const updatedContact = await contactsService.update(persons[person].id, newPerson);
setPersons(persons.concat(updatedContact));
setMessage({text: `Updated ${newName}`, type: 'notification'})
}
} else {
const newContact = await contactsService.create(newPerson);
// console.log("NEW: ", newContact);
setPersons(persons.concat(newContact));
setMessage({text: `Added ${newName}`, type: 'notification'})
}
setNewName('')
setNewNumber('')
} catch (error) {
setMessage({text: `Error: ${error}`, type: 'error'})
}
}
浏览器输出:
Failed to create contact. Error: Error: Request failed with status code 400 contacts.js:18:16
NEW: undefined
尽管 create() 失败,但前端显示成功消息,因为代码执行没有停止。
【问题讨论】:
-
两个问题,1.
searchPeople()是同步的,2.你说的错误是什么? -
@JeremyThille searchPeople() 只是一个地图功能。 create() 中的错误被捕获,但在 addPerson() 中没有被捕获。
-
如果
searchPeople()是.map()函数,为什么它会返回-1? map 返回一个数组,而不是一个数字 -
const searchPeople = (name) => { return persons.map(person => person.name).indexOf(name); } -
我对 searchPeople 没有意见。
标签: javascript async-await try-catch