async\/await

promise

var request = require('request'); 
function getRandomPonyFooArticle () { 
    return new Promise((resolve, reject) => { 
        request('https://ponyfoo.com/articles/random', (err, res, body) => { 
            if (err) { reject(err); return; } 
            resolve(body); 
        }); 
    }); 
}
var hget = require('hget'); 
var marked = require('marked'); 
var Term = require('marked-terminal'); 

printRandomArticle(); 
function printRandomArticle () { 
    getRandomPonyFooArticle() 
    .then(html => hget(html, { 
        markdown: true, 
        root: 'main', 
        ignore: '.at-subscribe,.mm-comments,.de-sidebar' 
    }))
    .then(md => marked(md, { renderer: new Term() }))
    .then(txt => console.log(txt))
    .catch(reason => console.error(reason)); 
}

generators

function getRandomPonyFooArticle (gen) { 
    var g = gen(); 
    request('https://ponyfoo.com/articles/random', (err, res, body) => { 
        if (err) { 
            g.throw(err); 
            return; 
        } g.next(body); 
    }); 
} 

getRandomPonyFooArticle(function* printRandomArticle () { 
    var html = yield; 
    var md = hget(html, { 
        markdown: true, 
        root: 'main', 
        ignore: '.at-subscribe,.mm-comments,.de-sidebar' 
    }); 
    var txt = marked(md, { renderer: new Term() }); 
    console.log(txt); 
});

async\/await


function getRandomPonyFooArticle () {  
    return new Promise((resolve, reject) => {
        request('https://ponyfoo.com/articles/random', (err, res, body) => {  
            if (err) { 
                reject(err); 
                return; 
            }  
            resolve(body);  
        });  
    }); 
}


read(); 

async function read () { 
    var html = await getRandomPonyFooArticle(); 
    var md = hget(html, { 
        markdown: true, 
        root: 'main', 
        ignore: '.at-subscribe,.mm-comments,.de-sidebar' 
    }); 
    var txt = marked(md, { renderer: new Term() }); 
    console.log(txt); 
}

Again, – and just like with generators – keep in mind that you should wrap await in try \/ catch so that you can capture and handle errors in awaited promises from within the async function.

results matching ""

    No results matching ""