erikpalla
3/10/2017 - 7:44 AM

generator + coroutine patterns

generator + coroutine

import co from 'co';

function asyncReduce(array, handler, startingValue) {
  return co(function* () {
    let result = startingValue;

    for (value of array) {
      // however, `co` does not wrap simple values into Promise
      // automatically, so we need to do so
      result = yield Promise.resolve(handler(result, value));
    }

    return result;
  });
}

function createLinks(links) {
  return asyncReduce(
    array,
    async (resolvedLinks, link) => {
      const newResolvedLink = await createLink(link);
      return resolvedLinks.concat(newResolvedLink);
    },
    []
  );
}

const links = [url1, url2, url3, url4, url5];
createLinks(links);
//module for coroutine exist under co
// const co = require('co');

const url = 'http://someaddresshere.com'
const fetch = require('node-fetch');

function* createQuoteFetcher(){
  const response = yield fetch(url);
  const quote = yield response.json();
  return `${quote.quoteText} -${quote.quoteAuthor}`;
}

const coroutine = (gen) => {
  const generator = gen();
  
  const handle = (result) => {
    if(result.done) return Promise.resolve(result.value);
    
    return Promise.resolve(result.value)
    .then(res => handle(generator.next(res)))
  }
  
  return handle(generator.next());
}

const quoteFetcher = coroutine(createQuoteFetcher);
quoteFetcher.then(quote => console.log(quote));