Как я могу обработать несколько зависимых запросов в саге? - PullRequest
1 голос
/ 03 июня 2019

Я пытаюсь сделать два запроса, один для сохранения изображения, другой для сохранения продукта с URL-адресом, полученным из первых запросов

Это то, что я хочу сделать первое: сохранить изображение товара (я использую axios для запросов) второе: получить URL из 'productImage' и затем включить его в параметры, чтобы сохранить

это мой код

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

1 Ответ

0 голосов
/ 03 июня 2019

Лучший шаблон здесь - разделить вашу сагу (createProduct) на две отдельные саги:

  • 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* для составления нескольких саг последовательным способом .

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

Добро пожаловать в stackoverflow!

...