Fetch API & Async Await

时间:2022-08-11 12:29:13

Fetch API & Async Await



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);
}
} // demo const promiseData = getDatas(`https://cdn.xgqfrms.xyz/json/ssr/posts.json`); promiseData.then(data => console.log(`promiseData`, data));

Fetch API & Async Await


SSR


"use strict"; /**
*
* @author xgqfrms
* @license MIT
* @copyright xgqfrms
* @created 2020-02-23
* @modified
*
* @description
* @augments
* @example
* @link
*
*/ const log = console.log; const puppeteer = require('puppeteer');
const handlebars = require('handlebars');
const fetch = require('node-fetch'); const fs = require('fs');
const path = require('path');
const util = require('util');
const readFile = util.promisify(fs.readFile); class Poster {
constructor(dom) {
this.dom = dom;
}
async fetchData(url) {
const data = await fetch(url).then(res => res.json());
// const data = await fetch(url).then(res => res.json()).catch(err => log(`fetch error`, err));
return data;
}
async html() {
try {
const data = {
timestamp: new Date().getTime(),
};
const templatePath = path.resolve('path', 'to', './poster-template.html');
const content = await readFile(templatePath, 'utf8');
// compile and render the template with handlebars
const template = handlebars.compile(content);
log(`template \n`, template);
return template(data);
} catch (error) {
throw new Error('Cannot create Poster HTML template.', error)
}
}
async screenshot() {
const html = await this.html();
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setContent(html);
// await page.goto(url);
const screenshot = await page.screenshot({
path: 'poster-template-ssr.png',
fullPage: true,
});
await browser.close();
return screenshot;
}
}