Skip to content Skip to sidebar Skip to footer

How To Use A Generator Function As A Callback Inside A Promise Returned By Fetch Call?

Is the above possible ? I'm not getting the consoled output when the callback function is a generator, which means that the control is not passing to the callback function(generat

Solution 1:

I guess you can do. When the generator function is run it will generate a generator object and it will be passed to the next then stage at where you can initiate the generator. Let's see...

var pr = Promise.resolve(42);
pr.then(function*(n){ yield n; yield n / 2; yield37})
  .then(it => {console.log(it.next().value);
               console.log(it.next().value);
               console.log(it.next().value);
              });

Solution 2:

Is the above possible?

No. The then method will simply call the generator function and create a generator, but then discard it fulfill the chained promise, without advancing it. Whenever you want to use generators, you actually need something that runs them.

The real reason I want to do it this way is that I have to call another fetch request using the 'call' helper function of redux-saga from the above callback which can be called only from a generator function.

Nope. You don't have to call call from an arbitrary generator function. You can can call and yield a call() from a generator function that is used by redux-saga.

In any case, your code should look like this:

let response = yieldtake(fetch(url, {
    credentials: 'same-origin',
    ...options
}));
response = yieldtake(response.json());
console.log("httpStatusCode", response.httpStatusCode)

Solution 3:

Taking a long shot here. In order to iterate through a generator function you need to be able to call 'gen.next()'. Which is not possible after providing an anonymous function to '.then'.

I am not familiar with redux-saga, but from what I understand you try something similar.

functionresponse (data) {
   console.log("httpStatusCode", data.httpStatusCode);
}


fetch(url, {...})
   .then(function (d) {
      var gen = response(d);
   })

You can then pass gen to be used in redux-saga.

Post a Comment for "How To Use A Generator Function As A Callback Inside A Promise Returned By Fetch Call?"