Yield call returns 一个承诺

Yield call returns a promise

所以我正在尝试学习 react-redux-saga。我正在构建一个简单的应用程序,它只是从 API 中获取用户数据并显示它。这是我的传奇中的生成器函数:

export function* fetchImage() {
      try {
        const response = yield call(fetch, 'https://randomuser.me/api/');
        console.log("Response 111", response);
        const responseBody = response.json();
        yield put(setImage(response));
      } catch (e) {
        yield put(fetchFailed(e));
      }
      return;

    }

它只是对 url 进行 yield 调用,然后分派一个动作。然而,响应对象并没有以 JSON 的形式返回,相反它看起来像是 returning 一些响应对象:

我不确定如何处理这个对象。如果您直接通过浏览器点击 URL,它 return 是一个 JSON 对象。我怎样才能达到 return JSON?

所以我的 response.json() 正在 returning 这个对象:

看起来我想要的对象在 [[PromiseValue]] 中。那是什么以及如何获得我的价值?

您始终可以在解析后访问响应对象的主体:

const response = yield call(fetch, 'https://randomuser.me/api/'); const responseBody = yield response.json(); // HERE is what you want

只是完成相同工作的另一种方法,使用 call 方法。

const response = yield call(fetch, 'https://randomuser.me/api/');
const body = yield call([response, 'json']);
console.log(body)

另一种方式

const body =  yield call([response, response.json]);