[英]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的“调用”帮助函数从上述回调中调用另一个获取请求,该回调只能从生成器函数中调用。
以上可能吗?
否then
方法将只调用生成器函数并创建一个生成器,但随后丢弃它以履行链式诺言而不进行推进。 每当您要使用生成器时,实际上就需要运行它们的东西。
我要这样做的真正原因是,我必须使用redux-saga的“调用”帮助函数从上述回调中调用另一个获取请求,该回调只能从生成器函数中调用。
不。 您不必从任意生成器函数调用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)
我想你可以做。 运行generator函数时,它将生成一个generator对象,并将其传递到下一个可以启动生成器的阶段。 让我们来看看...
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); });
在这里远射。 为了迭代生成器函数,您需要能够调用“ gen.next()”。 为'.then'提供匿名函数后,这是不可能的。
我对redux-saga并不熟悉,但是据我了解,您可以尝试类似的方法。
function response (data) {
console.log("httpStatusCode", data.httpStatusCode);
}
fetch(url, {...})
.then(function (d) {
var gen = response(d);
})
然后,您可以传递要在redux-saga中使用的gen
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.