Saturday, 6 May 2017

Why aren't these two ways of making an async call (one uses a promise, the other a generator) producing the same results?

I have a small node script that fetches users from Github using node-fetch (window.fetch compatible API on Node.js runtime). I then console.log the users, as can be seen below, using the returned Promise from fetch:

import fetch from 'node-fetch';
import "babel-polyfill";

const fetchUsers = lastReceivedId =>
  fetch(`https://api.github.com/users?since=${lastReceivedId}`);

console.log("Promise-based:");
fetchUsers(0)
  .then(response => response.json())
  .then(response => console.log(response))
  .catch(err => console.error(err));

The above works perfectly.

I now want to do the same thing using a generator together with the promise:

import fetch from 'node-fetch';
import "babel-polyfill";

const fetchUsers = lastReceivedId =>
  fetch(`https://api.github.com/users?since=${lastReceivedId}`);

function* main() {
  try {
    const res = yield fetchUsers(0);
    console.log("Response in generator is ", res);
  } catch (err) {
    console.log(err);
  }
}

console.log("Generator-Promise-based:")
const it = main();
const p = it.next().value;
p.then(
  function(response) {
    console.log("initial response is ", response.json())
    it.next(response.json())
  },
  err => it.throw(err)
);

This version does not work. The output is:

Generator-Promise-based:
initial response is  Promise {}
Response in generator is  Promise {}

Why aren't these two code snippets producing the same result?



via evianpring

No comments:

Post a Comment