简体   繁体   English

生成器功能不显示我的数据,如何访问它?

[英]Generator functions dont show my data, how to access it?

I have to invoke an API using sagas and generator function. 我必须使用sagas和generator函数调用API。 Here is my code: 这是我的代码:

export function* fetchCreate(data) {
  try {
    const options = jsonBodyOptions(data);
    const tagResponse = yield call(
      fetchJson,
      apiPath + '/fetch',
      tagOptions
    );
    return tagResponse;
  } catch (err) {
    console.log(err);
  }
}

export function* callFetch(data)  {
   const response = fetchCreate(data);
}

If I print fetchCreate() , I see Generator function printed. 如果我打印fetchCreate() ,我会看到打印生成器函数。

I want to invoke that generator function from another function in the same file. 我想从同一文件中的另一个函数调用该生成器函数。 I mainly want the response from that function but basically its returning a generator. 我主要想要该函数的响应,但基本上它返回一个生成器。 How can I retrieve the response from it? 如何从中检索响应?

Try using yield call(...) 尝试使用yield call(...)

export function* callFetch(data) {
   const response = yield call(fetchCreate, data);
}

If fetchJson returns a promise, then you can optionally convert fetchCreate into a plain function that returns a promise instead of a generator because yield call works with functions that return promises. 如果fetchJson返回一个promise,那么你可以选择将fetchCreate转换为一个返回promise而不是生成器的plain函数,因为yield call与返回promises的函数一起使用。

export function fetchCreate(data) {
  try {
    const options = jsonBodyOptions(data);
    return fetchJson(apiPath + '/fetch', tagOptions);    
  } catch (err) {
    console.log(err);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM