javascript - React Native: Chain Async Calls. e.g to AsyncStorage? -
i'm trying chain several calls asyncstorage.getitem() cannot seem calls trigger in correct order. seem manage drop out of loop last item completed before earlier items. appears react uses different syntax promises how jquery work.
in example trying chain calls vars v1, v2, v3. v3 triggers refresh of ui vars v1 , v2 required. code 2 chained vars follows:
asyncstorage.getitem("v1") .then( (value) => { if (value !== null){ varcollection.v1 =value } } ) .then( () => { asyncstorage.getitem("v3") .then((value) => { if (value !== null){ varcollection.v3 = value; }else{ varcollection.v3 = "default value"; } }) .done() }) .done();
this appears work may luck causing work when add link chain, things go wrong.
asyncstorage.getitem("v1") .then( (value) => { if (value !== null){ varcollection.v1 =value } } ) .then( () => { asyncstorage.getitem("v2") .then((value) => { if (value !== null){ varcollection.v2 = value; } }) .done() }) .then( () => { asyncstorage.getitem("v3") .then((value) => { if (value !== null){ varcollection.v3 = value; }else{ varcollection.v3 = "default value"; } }) .done() }) .done();
this results in v3 altering , triggering state of app change though v2 may not have been assigned yet.
calling console.log() on each of vars in props.varcollection getinitialstate() of child elements shows v1 present v2 isn't or vice versa. have tried nesting calls create chain realised gets messy quickly.
* update * further slacks , bergi's suggestions have tried following:
asyncstorage.getitem("v1") .then((value) => { if (value !== null){ v1 = value; } }) .then( () =>{ return( asyncstorage.getitem("v2") .then((value) => { if (value !== null){ v2 = value; } }) ) }) .then( () => { return( asyncstorage.getitem("v3") .then((value) => { if (value !== null){ v3 = value; } }) ) }) .done();
and
asyncstorage.getitem("v1") .then((value) => { if (value !== null){ v1 = value; } }) .then( () => ( asyncstorage.getitem("v2") .then((value) => { if (value !== null){ v2 = value; } }) ) ) .then( () => ( asyncstorage.getitem("v3") .then((value) => { if (value !== null){ v3 = value; } }) ) ) .done();
but still stuck @ second call.
* /update *
what correct way chain async calls in react native?
i'm not sure why suggested syntax bergi did not work found separating call , assignment before , after statement allowed strict control of ordering , return statement should return promise last call in each block. may not best way it, seems work quite sequential synchronous reads.
asyncstorage.getitem("v1") .then( (value) => { this.setstate({v1:value}) return asyncstorage.getitem("v2") } ) .then( (value) => { this.setstate({v2: value}) return asyncstorage.getitem("v3") } ) .then( (value) => { this.setstate({v3:value}) return asyncstorage.getitem("v4") } ) .then( (value) => { return this.setstate({v4:value}) } ).done();
you can see in action @ https://rnplay.org/plays/51t0cq
Comments
Post a Comment