Reputation: 1448
return fetch(url, {
credentials: 'same-origin',
...options
})
.then(response => response.json())
.then(function*(response) {
console.log("httpStatusCode", response.httpStatusCode)
})
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(generator). 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.
Upvotes: 0
Views: 4524
Reputation: 1384
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.
function response (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.
Upvotes: 0
Reputation: 26161
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; yield 37})
.then(it => {console.log(it.next().value);
console.log(it.next().value);
console.log(it.next().value);
});
Upvotes: 2
Reputation: 664630
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 = yield take(fetch(url, {
credentials: 'same-origin',
...options
}));
response = yield take(response.json());
console.log("httpStatusCode", response.httpStatusCode)
Upvotes: 2