如何在 fetch 调用返回的承诺中使用生成器函数作为回调?

How to use a generator function as a callback inside a promise returned by fetch call?

return fetch(url, {
    credentials: 'same-origin',
    ...options
  })
  .then(response => response.json())
  .then(function*(response) {
    console.log("httpStatusCode", response.httpStatusCode)
  })

以上可能吗? 当回调函数是生成器时,我没有得到控制台输出,这意味着控件没有传递给回调函数(生成器)。 我想这样做的真正原因是我必须使用 redux-saga 的 'call' 辅助函数从上面的回调中调用另一个获取请求,它只能从生成器函数中调用。

Is the above possible?

没有。 then 方法将简单地调用生成器函数并创建一个生成器,然后 丢弃它 履行链式承诺,而不推进它。每当您想使用生成器时,您实际上都需要运行它们的东西。

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.

没有。您不必从任意生成器函数调用 call。您可以从 redux-saga.

使用的生成器函数中调用 yield 一个 call()

无论如何,您的代码应该如下所示:

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

这里远射。为了遍历生成器函数,您需要能够调用 'gen.next()'。在为'.then'提供匿名函数后这是不可能的。

我不熟悉 redux-saga,但据我了解,您可以尝试类似的东西。

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


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

然后你可以传递 gen 以在 redux-saga 中使用。

我想你可以做到。当生成器函数为 运行 时,它将生成一个生成器对象,并将传递到下一个 then 阶段,您可以在该阶段启动生成器。让我们看看...

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