I have below arrow function -
const handleSubmit=()=>{
const tObject={
tId : store.Id,
tAction:store.Action,
tContent:store.content
}
let contentStatus=[];
if(storeContent!=null){
contentStatus = storeContent.map((item:IContent)=>({contentId:item.contentId , content:item.content}));
}
submitRequest(tObject,contentStatus);
}
submitRequest
is another arrow function which makes api call.
What is happening here is submitRequest
sometimes gets called before tObject
and contentStatus
objects get assigned to their respective values. This makes api call to be called with empty values.
How can I make sure submitRequest
is called after assignment of tObject
and contentStatus
?
Edit1 :
Can I assign object with await ?-
const tObject=await{
tId : store.Id,
tAction:store.Action,
tContent:store.content
}
Note :- assume this with handleSubmit
marked as async
.
CodePudding user response:
Utilize Async/Await keywords to ensure the code flow stops until getObject()
has returned its value successfully:
const getObject = () => {
return { tId : store.Id,tAction:store.Action, tContent:store.content }
}
const handleSubmit= async ()=>{
const tObject = await getObject()
...
...
}
Edit: Note while using await you have to make the function async as done in above example.
CodePudding user response:
Method: 2 Without await keyword in the HandleFunction, since we expect just an object not a resolved value/error result.
async getObject = () => {
return { tId : store.Id,tAction:store.Action, tContent:store.content }
}
const handleSubmit = () => {
// this will wait getValue() to return the result and then proceed with next code flow
getObject().then(() => {
let contentStatus=[];
if(storeContent!=null){
contentStatus = storeContent.map((item:IContent)=>({contentId:item.contentId , content:item.content}));
}
submitRequest(tObject,contentStatus);
});
}