[译]理解Javascript的异步等待

前端开发 作者: 2024-08-21 11:00:02
原文链接: "https://ponyfoo.com/articles/understanding javascript async await" 作者: "Nicol&


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))
      );
    }
  });
}


原创声明
本站部分文章基于互联网的整理,我们会把真正“有用/优质”的文章整理提供给各位开发者。本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
本文链接:http://www.jiecseo.com/news/show_66054.html