How to use a generator function as a callback insi

2019-09-05 01:50发布

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.

3条回答
Bombasti
2楼-- · 2019-09-05 02:04

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)
查看更多
Viruses.
3楼-- · 2019-09-05 02:04

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.

查看更多
一纸荒年 Trace。
4楼-- · 2019-09-05 02:08

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

查看更多
登录 后发表回答