我正尝试提出两个请求,一个保存图像,另一个请求保存具有第一个请求获得的url的产品
这就是我要做的 首先:保存产品图片(我正在使用axios进行请求) 第二:从“ 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);
}
答案 0 :(得分:0)
最好的方法是将您的传奇(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*
运算符在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);
}
}
欢迎来到stackoverflow!