Monday, May 13, 2024
166
rated 0 times [  172] [ 6]  / answers: 1 / hits: 29183  / 8 Years ago, wed, june 8, 2016, 12:00:00

I am working on a javascript project that needs to get some data and process it, but I am having trouble with the asynchronous nature of JavaScript. What I want to be able to do is something like the following.



//The set of functions that I want to call in order
function getData() {
//gets the data
}

function parseData() {
//does some stuff with the data
}

function validate() {
//validates the data
}

//The function that orchestrates these calls
function runner() {
getData();
parseData();
validate();
}


Here I want each function to wait for completion before going on to the next call, as I am running into the situation where the program attempts to validate the data before it has been retrieved. However, I also want to be able to return a value from these functions for testing, so I can't have these functions return a boolean value to check completion. How can I make javascript wait on the function to run to completion before moving on to the next call?


More From » asynchronous

 Answers
14

Use promises:





//The set of functions that I want to call in order
function getData(initialData) {
//gets the data
return new Promise(function (resolve, reject) {
resolve('Hello World!')
})
}

function parseData(dataFromGetDataFunction) {
//does some stuff with the data
return new Promise(function (resolve, reject) {
resolve('Hello World!')
})
}

function validate(dataFromParseDataFunction) {
//validates the data
return new Promise(function (resolve, reject) {
resolve('Hello World!')
})
}

//The function that orchestrates these calls
function runner(initialData) {
return getData(initialData)
.then(parseData)
.then(validate)
}

runner('Hello World!').then(function (dataFromValidateFunction) {
console.log(dataFromValidateFunction);
})





Not only are they easy to grasp, it makes total sense from a code readability stand point. Read more about them here. If you are in a browser environment, I recommend this polyfill.


[#61845] Tuesday, June 7, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kylanalis

Total Points: 438
Total Questions: 85
Total Answers: 102

Location: Barbados
Member since Sun, Nov 27, 2022
1 Year ago
kylanalis questions
Sat, Oct 2, 21, 00:00, 3 Years ago
Tue, Oct 13, 20, 00:00, 4 Years ago
Thu, Feb 13, 20, 00:00, 4 Years ago
Tue, Jan 7, 20, 00:00, 4 Years ago
;