【发布时间】:2021-02-07 19:15:12
【问题描述】:
我正在从客户端向服务器发出获取请求。我已经确认它获取数据并将其成功发送回客户端。但是,在 .then 链接中,当我 console.log res.json() 时,它说承诺仍在等待中。
我已尝试添加 async、await 和/或 try、catch 短语,您将在下面的代码中看到。
我已经尝试了我所知道的一切。有没有办法解决这个问题?
下面是客户端使用fetch获取请求逻辑的代码:
let cache = {};
async function getMsg() {
try {
await fetch('/api/getMsg')
.then(res => {console.log(res.json()); return res.json()})
.then(data => {
console.log('got data', data);
const list = document.createElement('li');
const button = document.createElement('button');
const ul = document.getElementById('message-list');
// data is an array whose elements are message objects
data.forEach((obj)=> {
if (!cache.obj._id) {
list.innerText(obj.message);
button.innerText('Delete');
button.setAttribute('class', 'del');
button.addEventListener('click', () => {
fetch(`/api/${obj._id}`)
.then(res => res.json())
.then(data => {
window.alert(`Message with id of ${data} has been deleted!`);
})
});
document.querySelector('body').append(ul);
ul.append(list)
ul.append(button);
cache.obj._id = obj.message;
}
});
})
} catch {
(err => console.log(err));
}
}
控制台上的错误信息: Uncaught (in promise) SyntaxError: Unexpected token O in JSON at position 0
【问题讨论】:
标签: javascript promise async-await fetch try-catch