Path: csiph.com!eternal-september.org!feeder.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: Ben Bacarisse Newsgroups: comp.lang.javascript Subject: Re: synchronizing asynchronus request Date: Sun, 16 Apr 2017 11:09:43 +0100 Organization: A noiseless patient Spider Lines: 56 Message-ID: <8760i4pst4.fsf@bsb.me.uk> References: Mime-Version: 1.0 Content-Type: text/plain; charset=iso-8859-1 Content-Transfer-Encoding: 8bit Injection-Info: mx02.eternal-september.org; posting-host="0a20cc05eb093678225a37756d36945a"; logging-data="14574"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX190XuzNcUu3ppKpAckjq+So1Kq81tFXwXI=" Cancel-Lock: sha1:TEpTwX3IVuio0VebgXYEuKJSmKw= sha1:5bGH08cGVW1FE8cvUXk1nsug4RA= X-BSB-Auth: 1.70e9bdb678e169b34273.20170416110943BST.8760i4pst4.fsf@bsb.me.uk Xref: csiph.com comp.lang.javascript:33020 Une Bévue writes: > I've an app requesting different values to a websocket server : > albums ; > cameras ; > locations ; > persons ... > ... > > Then i have answers being asynchronous, but I'd like to synchronize > all the answers at the time of the latest. > > The code is like (ES6) : > > let requestAlbums = {database: 'photos', ...}; > this.props.socket.sendRequest(requestAlbums, (message) => { > this.setState({albums: message.results.albums}); > }); > > let requestCameras = {database: 'photos', ...}; > this.props.socket.sendRequest(requestCameras, (message) => { > this.setState({cameras: message.results.cameras}); > }); > > let requestLocations = {database: 'photos', ...}; > this.props.socket.sendRequest(requestLocations, (message) => { > this.setState({locations: message.results.locations}); > }); > > let requestPersons = {database: 'photos', ...}; > this.props.socket.sendRequest(requestPersons, (message) => { > this.setState({persons: message.results.persons}); > }); > > I'd like to "wait" for the latest result (aka "persons") in order to > have only one this.setState like : I think you want to do something when all the results are in. The last one in may be the first one requested -- you can't assume that "persons" will be the last. (BTW, "latest" does not quite mean what you think it does -- the "latest result" is not the "last result", it is the result most recently received.) One way would be to count (or other record) the results as they come in. The handler (the function that currently calls setState) could increment a result count and call a function to use the result when the counter becomes 4. It's not clear why you want only one call to setState because that function could be doing exactly what I've described -- every time setState is called it checks if the result that's being recorded is the last price of the picture. -- Ben.