reactjs dispatch promise continuously after specific time - javascript

In my react component I am calling an action in ComponentDidMount() like this:
componentDidMount() {
const { actions } = this.props
function save_project_continiously() {
console.log("inside")
actions.save_project().then(save_project_continiously)
}
save_project_continiously()
}
Here I am calling an action continuously.. My actions is like:
export function save_project() {
return (dispatch, getState) => {
setTimeout(() => {
return dispatch(manage_data()).then(response => {
console.log("Hellooww world")
return response
})
}, 3000)
}
}
When I do this it gives me error saying .then() is not a function in ComponentDidMount() ..
If I do
export function save_project() {
return (dispatch, getState) => {
return dispatch(manage_data()).then(response => {
console.log("Hellooww world")
return response
})
}
}
It is called continuously but I want it to be called continuously after specific time.
I tried this:
export function save_project() {
return (dispatch, getState) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
return dispatch(manage_data()).then(response => {
console.log("Hellooww world")
return response
})
}, 3000)
})
}
}
But it is only called once.. Does not give any error but it only calls once..
What I want is I want to call an actions continuosly after specific time after completing the action.
Here I want to call save_project and after completing it I again want to call it after 3 seconds and go on continuously ..
How can I make it happen ??
Any suggestions ??
Thanks in advance

In this code, you're wrapping promise in promise, but what you actually want to do is execute this code again on successful promise resolve.
export function save_project() {
// So this code does return callback, so it does not return promise
// in your first example.
return (dispatch, getState) => {
// Then this code returns promise, but it never gets resolved.
return new Promise((resolve, reject) => {
setTimeout(() => {
// Then you return promise from set timeout, but it
// is doubtful as well
return dispatch(manage_data()).then(response => {
console.log("Hellooww world")
return response
})
}, 3000)
})
}
}
What you really want to do is:
// Just return promise of dispatch instead of wrapping it in
// a callback.
export function save_project() {
return dispatch(manage_data());
}
// Then use set timeout here
function save_project_continiously() {
console.log("inside")
actions.save_project().then(() => {
setTimeout(save_project_continiously, 3000);
});
}
Or if you really want a callback in save_project, you need to call it properly with proper args as in your example they're undefined anyway.

Try setInterval()
export function save_project() {
return new Promise((resolve, reject) => {
setTimeout(() => {
dispatch(manage_data()).then(response => {
resolve(response);
}, error => {
reject(response);
})
}, 3000)
});
}

Related

Redux - Asynchronous response from web socket request

I have a websocket interface which I implemented so that I can use to send requests.
The problem is that the response is asynchronous and it initially returns the empty array because retObj is not updated from the callback function that I sent in. How can I make this function so that it will return the populated array when it has been updated.
This is how my Service looks like:
import * as interface from '../webSocket'
const carService = () => {
return {
getCars: () => {
interface.sendRequest(function (returnObject) {
//
}).then(d => d)
}
}
}
export default carService()
And this is how my action looks like:
import { GET_CARS } from '../constants'
import carService from '../carService'
export const getCars = () => async (dispatch) => {
try {
const cars = await carService.getCars()
console.log("At cars actions: ", cars) // logs: Array []
dispatch(getCarsSuccess(cars))
} catch (err) {
console.log('Error: ', err)
}
}
const getCarsSuccess = (cars) => ({
type: GET_CARS,
payload: cars
})
You simply have to wrap your callback into promise, since it was not a promise to begin with, which is why you cannot use then or await
import * as interface from '../webSocket'
const carService = () => {
return {
getCars: () => {
return new Promise(resolve => interface.sendRequest(function (returnObject) {
resolve(returnObject.msg)
}));
}
}
}
export default carService()
The problem is, you cant await a function unless it returns a Promise. So, as you can guess, the problem lies in carService.getCars's definition. Try this:
getCars: () => {
return new Promise((resolve, reject) => {
interface.sendRequest(function(returnObject) {
// if theres an error, reject(error)
resolve(returnObject);
})
})
}
Or, if sendRequest os am async function, simply return the return value of sendRequest:
getCars: () => {
return interface.sendRequest()
}

Angular 8 return observable after chain of async calls

I have a simple function that calls 3 async functions one after another like this:
getData() {
this.getUsers('2')
.pipe(
flatMap((data: any) => {
return this.getPosts(data.id);
}),
flatMap((data: any) => {
return this.getPosts(data[0].userId);
})
).subscribe(results => {
return new Observable((observer) => {
observer.next(results);
observer.complete();
});
});
}
I would like someway to be able to call something like:
this.getdata.subscribe() and that be called when all 3 flatMaps are completed. I assume I would have to have the getData() function return an observable which I tried to do at the bottom but it does not work and I am not able to call .subscribe on the getData() function.
Try like this:
Working Demo
getData() {
return this.getUsers('2')
.pipe(
flatMap((data: any) => {
return this.getPosts(data.id);
}),
flatMap((data: any) => {
return this.getPosts(data[0].userId);
})
)
}

wait for promise before Promise all JavaScript

I have this array of promises :
return function (dispatch, getState) {
Promise.all([
dispatch(getThis()),
dispatch(getThat()),
dispatch(getThese()),
dispatch(getThose()))]
).then(() => {
let state = getState();
dispatch({
//dispatch
});
}).catch(function (err) {
console.log(err);
});
}
But in fact I want getThis() to be finished before calling any other dispatch because they are all dependant on the return of getThis().
How to handle this?
Thanks a lot!
EDIT my function looks like this:
export function getThis() {
return function (dispatch, getState) {
return new Promise((resolve, reject) => {
axios.get('api/this/' + lienBuild).then((response) => {
resolve(dispatch({type: "FETCH_THIS", data: response.data}));
});
})
};
}
See FrankerZ's comment, apparently this dispatch function is a standard Redux thing (I don't use Redux) and it doesn't return a promise, so it doesn't make sense to use Promise.all on it.
But answering the promises aspect of "how would I wait for getThis first": Just move it to the beginning of the chain:
return function (dispatch, getState) {
dispatch(getThis()) // First this, then...
.then(result => Promise.all([ // ...these
dispatch(getThat(result)), // (I've passed the result to all three, but...)
dispatch(getThese(result)),
dispatch(getThose(result))
]))
.then(() => {
let state = getState();
dispatch({
//dispatch
});
}).catch(function (err) {
console.log(err);
});
}
or without the dispatch, since apparently that's wrong:
return function (dispatch, getState) {
getThis() // First this, then...
.then(result => Promise.all([ // ...these
getThat(result), // (I've passed the result to all three, but...)
getThese(result),
getThose(result)
]))
.then(() => {
let state = getState();
dispatch({
//dispatch
});
}).catch(function (err) {
console.log(err);
});
}
Side note about getThis: See this question and its answers. No need for new Promise when you already have a promise. I don't know whether that getThis code is correct in terms of Redux, but here's the same code not using new Promise unnecessarily:
export function getThis() {
return function(dispatch, getState) {
return axios.get('api/this/' + lienBuild).then(response => dispatch({type: "FETCH_THIS", data: response.data}));
};
}
or with destructuring and shorthand properties:
export function getThis() {
return function(dispatch, getState) {
return axios.get('api/this/' + lienBuild).then(({data}) => dispatch({type: "FETCH_THIS", data}));
};
}
or if you can use async/await:
export function getThis() {
return async function(dispatch, getState) {
const {data} = await axios.get('api/this/' + lienBuild);
return dispatch({type: "FETCH_THIS", data});
};
}

How to break chain in promise

I'm trying to limit the number of apis fetches in my project by saving them in a simple cache, key collection in mongodb. Is thera way to stop propagation of .then() inside Promise, without using async/await?
export const getData = (url: string) => {
return new Promise((resolve, reject) => {
findInCache(url)
.then((cached: string | null) => {
if (cached) {
resolve(cached);
}
})
.then(() => {
axios
.get(url)
.then(({data}) => {
setCache(url, data, TTL);
resolve(data);
})
.catch(e => reject(e));
});
});
};
Firstly, lets get rid of the Promise constructor anti-pattern - your function call inside the promise executor returns a promise, so, no need for anew Promise
Secondly, only run the second request if the result of the first is empty
export const getData = (url) => findInCache(url)
// here we return haveResult and avoid axios.get(url) altogether
.then((haveResult) => haveResult || axios.get(url)
// sometimes nested .then is useful like in this case
.then(({data}) => {
setCache(url, data, TTL);
return data;
})
);
you can just do this instead instead of chaining. if it is in cache then fetch from cache else get from url
export const getData = (url: string) => {
return new Promise((resolve, reject) => {
findInCache(url)
.then((cached: string | null) => {
if (cached) {
resolve(cached);
} else {
axios
.get(url)
.then(({data}) => {
setCache(url, data, TTL);
resolve(data);
})
.catch(e => reject(e));
}
})
});
};
When you return something result in then, this result is come into next then function. So, you can control what you would do in next then based on input parameter inCache. So you can do something like:
export const getData = (url: string) => {
return new Promise((resolve, reject) => {
findInCache(url)
.then((cached: string | null) => {
if (cached) {
resolve(cached);
return true;
}
return false;
})
.then((inCache) => {
if (!inCache) {
axios
.get(url)
.then(({data}) => {
setCache(url, data, TTL);
resolve(data);
})
.catch(e => reject(e));
}
});
});
};

Javascript - Redux actions don't run consecutively

I have a situation when I need 2 Redux Actions to be run consecutively.
The context is a user clicks on a Preview button, and I want to display a loader until the puzzle is done generating.
function mapDispatchToProps(dispatch) {
return {
onPreview: () => {
dispatch(generatePreview());
},
};
}
In order to do it, I use the middleware redux-thunk and the action I want to be executed first returns a Promise.resolve() and my second action is in the then():
export function generatingPreview() {
return dispatch => {
dispatch({
type: GENERATING_PREVIEW,
});
return Promise.resolve();
};
}
export function generatePreview() {
return (dispatch, getState) => {
dispatch(generatingPreview()).then(() => {
const state = getState();
const conf = state.getIn(['login', 'conf']).toJS();
const wordList = state.getIn(['login', 'wordList']);
try {
const newPuzzle = Wordfind.newPuzzleLax(wordList, conf);
dispatch(generatePreviewSuccess(newPuzzle));
} catch (err) {
dispatch(generatePreviewError(err.message));
}
});
};
}
export function generatePreviewError(error) {
return {
type: GENERATE_PREVIEW_ERROR,
error,
};
}
export function generatePreviewSuccess(payload) {
return {
type: GENERATE_PREVIEW_SUCCESS,
payload,
};
}
Unfortunately, the loader never appears. I console.logged the state setting the loading to true when my component renders, and it changes! I can see the log but not the loader, the component doesn't really re-render until the actions generatePreviewSuccess() or generatePreviewError() are dispatched. And it's not an issue from the loader, if I replace the newPuzzleLax function by a loop in order to make enough time to see it, I can see it!
My theory is this function Wordfind.newPuzzleLax(wordList, conf) that I use to generate the puzzle is blocking the queue of actions because on the Chrome Redux Tools I an see the first action appearing at the same time that the second one:
Link to the function.
If I add a 1-microsecond delay between the dispatch of the two actions, the loader appears... but I would really like to understand what is happening. Thank you in advance. If it's any help, I use the react-boilerplate
I also tried to transform the function generating the puzzle as an async one by doing this:
const wordFindAsync = async (wordList, conf) =>
Wordfind.newPuzzleLax(wordList, conf);
export function generatePreview() {
return (dispatch, getState) => {
dispatch(generatingPreview())
.then(() => {
const state = getState();
const conf = state.getIn(['login', 'conf']).toJS();
const wordList = state.getIn(['login', 'wordList']);
wordFindAsync(wordList, conf);
})
.then(res => dispatch(generatePreviewSuccess(res)))
.catch(err => {
dispatch(generatePreviewError(err.message));
});
};
}
In your second version you're not returning the Promise from wordFindAsync(wordList, conf) back into your original Promise chain, and so its not being resolved/waited on by then next then.
export function generatePreview() {
return (dispatch, getState) => {
dispatch(generatingPreview())
.then(() => {
const state = getState();
const conf = state.getIn(['login', 'conf']).toJS();
const wordList = state.getIn(['login', 'wordList']);
return wordFindAsync(wordList, conf); // 🌟 return your promise here
})
.then(res => dispatch(generatePreviewSuccess(res)))
.catch(err => {
dispatch(generatePreviewError(err.message));
});
};
}
Here's a simple example demoing the behavior I'm refering to.
This one will only wait 1 second until logging "done":
const waitOneSec = () =>
new Promise(resolve => {
console.log("waiting 1 secoond");
setTimeout(resolve, 1000);
});
waitOneSec()
.then(() => {
waitOneSec(); // Promise not returned
})
.then(() => console.log("done"));
Whereas this one will wait full 2 seconds until logging "done":
const waitOneSec = () =>
new Promise(resolve => {
console.log("waiting 1 secoond");
setTimeout(resolve, 1000);
});
waitOneSec()
.then(() => {
return waitOneSec(); // 🌟 Promise returned
})
.then(() => console.log("done"));
Hope that helps.

Categories

Resources