簡體   English   中英

生成器功能不顯示我的數據,如何訪問它?

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

我必須使用sagas和generator函數調用API。 這是我的代碼:

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

如果我打印fetchCreate() ,我會看到打印生成器函數。

我想從同一文件中的另一個函數調用該生成器函數。 我主要想要該函數的響應,但基本上它返回一個生成器。 如何從中檢索響應?

嘗試使用yield call(...)

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

如果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