我如何处理传奇中的多个依赖请求?

How can I handle multiple dependent requests in a saga?

我正在尝试提出两个请求,一个是保存图像,另一个是保存产品,其中 url 来自第一个请求

这就是我想做的 第一:保存产品图片(我正在使用 axios 请求) 第二:从 'productImage' 获取 url 然后将其包含在参数中以保存

这是我的代码

function* createProduct(action) {
  const { endpoint, params } = action.payload;
  try {   

    const productImage = yield call(new api().createImage, { endpoint, params });

     // I need to wait the url of the image and include it on the params for the second request before is executed
    // E.g. params.image = productImage.url
    const product = yield call(new api().createProduct, { endpoint, params });

    yield put({
      type: CREATE_PRODUCT_SUCCEED,
      payload: {
        product 
      }
    });
  } catch (e) {
    yield put({
      type: CREATE_PRODUCT_FAILED,
      payload: {
        ...e
      }
    });
  }
}

export default function* createProductWatcher() {
  yield takeEvery(CREATE_PRODUCT_EXECUTION, createProduct);
}

此处最好的模式是将您的 saga (createProduct) 拆分为两个单独的 sagas:

  • createImage - 将处理产品的图像创建
  • createProduct - 将使用给定的图像处理产品创建
// Creates the product image
function* createImage(action) {
    const { endpoint, params } = action.payload;
    try {
        const image = yield call(new api().createImage, { endpoint, params });
        yield put({
            type: CREATE_IMAGE_SUCCEED,
            // Here you pass the modified payload to createProduct saga
            payload: {
                endpoint,
                params: { image: image.url }
            }
        });
    } catch(e) {
        yield put({
            type: CREATE_IMAGE_FAILED,
            payload: {
                ...e
            }
        });
    }
}
//Creates the product with the image
function* createProduct(action) {
    const { endpoint, params } = action.payload;
    try {
        const product = yield call(new api().createImage, { endpoint, params });
        yield put({
            type: CREATE_PRODUCT_SUCCEED,
            payload: {
                product
            }
        });
    } catch(e) {
        yield put({
            type: CREATE_PRODUCT_FAILED,
            payload: {
                ...e
            }
        });
    }
}

然后使用内置的 yield* 运算符在 sequential way.

中组合多个 Sagas
// Another saga for chaining the results
function* invokeSagasInOrder(sagas) {
    try {
        const image = yield* createImage();
        yield* createProduct(image);
    } catch(e) {
        console.log(e);
    }
}

欢迎使用 Whosebug!