繁体   English   中英

如何在 JS 中使用 try、catch、.then 链接和异步等待来解析 promise?

[英]How do I resolve a promise using try, catch, .then chaining, and async await in JS?

我正在从客户端向服务器发出获取请求。 我已经确认它获取数据并将其成功发送回客户端。 但是,在 then 链接中,当我控制台记录 res.json() 时,它表示 promise 仍在等待中。

我已经尝试添加 async、await 和/或 try、catch 短语,您将在下面的代码中看到。

我已经尝试了我所知道的一切。 有办法解决这个问题吗?

下面是客户端使用fetch的get请求逻辑代码:

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

我认为这里最好的方法是根本不使用 async-await。 像这样:

 let cache = {}; function getMsg() { 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)); }

但是如果想使用 try-catch 和 async-await 语法,你可以这样尝试:

 let cache = {}; async function getMsg() { try { let res = await fetch('/api/getMsg'); let data = await res.json(); 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)); } }

我认为这应该有效

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM