【问题标题】:How do I resolve a promise using try, catch, .then chaining, and async await in JS?如何在 JS 中使用 try、catch、.then 链接和异步等待来解决承诺?
【发布时间】: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


    【解决方案1】:

    我认为这里最好的方法是根本不使用 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));
        }
    }

    我认为这应该可行

    【讨论】:

    • 非常感谢。最初我将它设置为您的第一个解决方案,但仍然出现相同的错误。当我尝试您的第二个解决方案时,没有显示错误。但是,'try' 短语的第 3 行的 console.log 甚至没有出现在控制台上。有关如何解决此问题的任何建议?
    • 控制台中没有显示任何内容吗?还是只是不显示数据?
    • 什么都不显示!这真的很奇怪..似乎它正在等待永远,因为它没有点击 console.log('got data', data)..
    • 您能检查一下开发者工具上的网络选项卡,看看那里是否有问题吗?
    • 您的响应内容类型是否可能不是 JSON?
    猜你喜欢
    • 2021-11-09
    • 2020-01-01
    • 1970-01-01
    • 2017-02-06
    • 2019-05-03
    • 2023-04-06
    • 2018-04-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多