xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

async & await & promise

async & await & promise

ES7


const f = async () => {
    return 1;
};

 
f().then(value => console.log(value)); 
// 1
// Promise {<resolved>: undefined}

f();
// Promise {<resolved>: 1}

chrome://extensions/


        async getNews() {
            try {
                const response = await fetch(`https://raw.githubusercontent.com/darkreader/darkreader.org/master/src/blog/posts.json?nocache=${Date.now()}`, { cache: 'no-cache' });
                const $news = await response.json();
                return new Promise((resolve, reject) => {
                    chrome.storage.sync.get({ readNews: [] }, ({ readNews }) => {
                        const news = $news.map(({ id, date, headline }) => {
                            const url = getBlogPostURL(id);
                            const read = this.isRead(id, readNews);
                            return { id, date, headline, url, read };
                        });
                        for (let i = 0; i < news.length; i++) {
                            const date = new Date(news[i].date);
                            if (isNaN(date.getTime())) {
                                reject(new Error(`Unable to parse date ${date}`));
                                return;
                            }
                        }
                        resolve(news);
                    });
                });
            }
            catch (err) {
                console.error(err);
                return null;
            }
        }



Fetch API & Async Await

practical demo

const fetchJSON = (url = ``) => {
    return fetch(url,
        {
            method: "GET",
            // mode: "no-cors",
            mode: "cors",
            credentials: "same-origin",
            headers: {
                "Content-Type": "application/json; charset=utf-8",
            },
        })
        .then(res => res.json())
        .then(
            (json) => {
                return json;
            }
        )
        .catch(err => console.log(`fetch error`, err));
};

// async / await
async function getDatas(url = ``) {
    try {
        return await fetchJSON(url);
    } catch (err) {
        console.error("getDatas error:\n", err);
    }
}


Promise & error catch

https://zh.javascript.info/promise-error-handling



posted @ 2018-12-13 21:49  xgqfrms  阅读(173)  评论(5编辑  收藏  举报