如何将生成器函数用作fetch调用返回的promise中的回调? [英] How to use a generator function as a callback inside a promise returned by fetch call?

查看:99
本文介绍了如何将生成器函数用作fetch调用返回的promise中的回调?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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.

推荐答案

我想你可以做到.运行generator函数时,它将生成一个generator对象,并将其传递到下一个可以启动生成器的阶段.让我们看看...

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

这篇关于如何将生成器函数用作fetch调用返回的promise中的回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆