I'm trying to use ES javascript api to get data from Elastic Search and show it in my React Redux Redux-Saga code.
function* getData() {
const response = async () => await client.msearch({
body: [
// match all query, on all indices and types
{},
{ query: { match_all: {} } },
// query_string query, on index/mytype
{ index: 'myindex', type: 'mytype' },
{ query: { query_string: { query: '"Test 1"' } } },
],
});
yield put(Success({
Data: response(),
}));
}
The problem is I don't know how to make the yield wait for the response to be resolved. Is there any other way to use a promise inside redux saga and es javascript-client ?
You should never be calling the await function directly inside the saga-generator, because redux-saga is for orchestrating the side-effects. Therefore, any time that you want to run a side-effect you should do it by yielding the side-effect through a redux-saga effect (usually: call or fork ).
You can transpile async/await into generators, but you can't do the reverse. As a userland library, redux-saga can handle asynchronous behavior in ways that async/await doesn't.
Redux Saga utilizes ES6 generator functions for this. Generators allow for synchronously written asynchronous code. A generator will automatically pause — or yield — at each asynchronous call until it completes before continuing.
An action creator, createPromiseAction() that you can use to define actions which return promises. We call an action that returns a promise a promise action. Saga helpers implementPromiseAction() , resolvePromiseAction() , and rejectPromiseAction() that you use to resolve or reject a promise action's promise.
I figured it out. Putting the answer here for anyone looking for it.
function* getData(data) {
const response = yield call(fetchSummary, data);
yield put(Success({
Data: response,
}));
}
async function fetchSummary(data) {
return await client.msearch({
body: [
// match all query, on all indices and types
{},
{ query: { match_all: {} } },
// query_string query, on index/mytype
{ index: 'myindex', type: 'mytype' },
{ query: { query_string: { query: data.query } } },
],
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With