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));
}
function getRandomPonyFooArticle (gen) {
var g = gen();
request('https://ponyfoo.com/articles/random',body) => {
if (err) {
g.throw(err); return;
}
g.next(body);
});
}
getRandomPonyFooArticle(function* printRandomArticle () {
var html = yield;
var md = hget(html,{
markdown: true,.de-sidebar'
});
var txt = marked(md,{
renderer: new Term()
});
console.log(txt);
});
read();
async function read () {
var html = await getRandomPonyFooArticle();
var md = hget(html,{
renderer: new Term()
});
console.log(txt);
}
async function asyncFun () {
var value = await Promise
.resolve(1)
.then(x => x * 3)
.then(x => x + 5)
.then(x => x / 2);
return value;
}
asyncFun().then(x => console.log(`x: ${x}`));
// <- 'x: 4'
async function read () {
var html = await getRandomPonyFooArticle();
var md = hget(html,{
renderer: new Term()
});
return txt;
}
async function write () {
var txt = await read();
console.log(txt);
}
read().then(txt => console.log(txt));
async function concurrent () {
var [r1,r2,r3] = await Promise.all([p1,p2,p3]);
}
async function concurrent () {
var [r1,r3] = await* [p1,p3];
}
const all = Promise.all.bind(Promise);
async function concurrent () {
var [r1,r3] = `await all([p1,p3])`;
}
read()
.then(txt => console.log(txt))
.catch(reason => console.error(reason));
npm i -g npm-run
npm i -D \
browserify \
babelify \
babel-preset-es2015 \
babel-preset-stage-3 \
babel-runtime \
babel-plugin-transform-runtime
echo '{
"presets": ["es2015","stage-3"],"plugins": ["transform-runtime"]
}' > .babelrc
npm-run browserify -t babelify example.js | node
async function example (a,b,c) {
example function body
}
function example (a,c) {
return spawn(function* () {
example function body
},this);
}
function spawn (genF,self) {
return new Promise(function (resolve,reject) {
var gen = genF.call(self);
step(() => gen.next(undefined));
function step (nextF) {
var next;
try {
next = nextF();
} catch(e) {
// 执行失败,并拒绝promise对象
reject(e);
return;
}
if (next.done) {
// 执行成功,处理promise对象
resolve(next.value);
return;
}
// 未完成,以yield标记的promise对象呗中断,并在此执行step方法
Promise.resolve(next.value).then(
v => step(() => gen.next(v)),e => step(() => gen.throw(e))
);
}
});
}