i'am using reflux of reactjs. From Store's action of reflux, i wrote a action to get data from asp.net web api, i think that just only way to get data which use to ajax, someone say with me, i can get data with a plugin jquery but i don't believe it because the $.ajax is best way. I search everything on google but i don't see to resolve for that. If you know something to resolve, please share with me, i really thanks.
Beside, i had a problem with global and local variable of ajax. Please review my code, you can see the bold text which never return a value, the problem which stay with the block of success, the list var isn't update when it outside of the block. What's up problem with that ? how can i fix that error ?
Thank you very much, again!
(function (Reflux, WorkHistoryActions, global) {
global.workhistoryStore = Reflux.createStore({
listenables: [WorkHistoryActions],
init: function () {
this.storyArr = [];
},
getItems: function (resume_id) {
console.log(resume_id)
**var list = [];**
$.ajax({
type: "get",
url: global.getHost() + "/api/workhistories/6969607988340821009",
dataType: 'json',
crossDomain: true,
success: function (data) {
$.each(data, function (i, v) {
**list.push(v);**
})
}
});
**return list;**
},
})
JavaScript is an event-driven system where AJAX requests are also Async and the response from the server is received asynchronously.
Using
async: false
is a bad practice as it will freeze your application and block any parallel execution.So with
async: true
(which is default), you can't call a function which makes an AJAX call and returns the response.Solution #1: Callbacks (old-school)
Modify your
getItems
function to receive another parameter which is a callback function, when you receive a response from the server, call that callback function and passlist
as a parameter to that function call.Example
How to use?
Solution #2: JavaScript Promises (recommended)
Return a JavaScript promise and set the callback using
then()
function. I use kriskowal's promise implementationExample
How to use?
I am not sure how to do it in reflux but in a normal flux architecture you would do like so:
The store registers to the dispatcher for the actions RECEIVED_WORK_HISTORY_ITEMS and FAILED_TO_RECEIVE_WORK_HISTORY_ITEMS, sets its data and then fires the change event.