Unfortunately the best way to solve this is to learn! I'd start with...
1) How closures work
http://stackoverflow.com/questions/1111 ... sures-workBasically, you can reference variables in a function's scope or any parent scope.2) How asynchronous calls work
http://stackoverflow.com/questions/1422 ... 3#14220323Basically, do not "return" a value when using async calls. Instead, pass it to another function which is dubbed a callback. Life does not pause for async calls.2a) AFTER you understand what an async call is, then you can benefit from an async library like
https://github.com/caolan/async2b) If you are feeling daring and have an idea of the above you can benefit from promise library instead like
https://github.com/petkaantonov/bluebird/These libraries are not necessary to learn and use Javascript but really help for lots of nested async calls.And keep in mind that functions are first-class citizens in JS, which means you can pass them around like variables, or assign variables to functions. For example:
var a = function someFunction (param) {
console.log(param);
}
a("Hello!"); // Outputs "Hello!"
function b(param) {
console.log(param);
}
b("Hello!!"); // Outputs "Hello!!"
var c = console.log;
c("Hello!!!"); // Outputs "Hello!!!"
// You can even declare a function, wrap it in parentheses, and run it with some parameters.
// Because it's a closure, it can still see other functions outside it.
(function(param) { c(param); })("Hello!!!!"); // Outputs "Hello!!!!"
// This doesn't work because someFunction was part of a's declaration
someFunction("Hello!"); // ReferenceError: someFunction is not defined
A solution to your code could be something like
function step1(params, callback) {
var result1 = "Step 1 has these params" + JSON.stringify(params);
callback(result1);
}
function step2(params, callback) {
var result2 = "Step 2 params = " + JSON.stringify(params);
callback(result2);
}
// Do something complicated
var startingParams = { hello: "there" };
step1(startingParams, function(step1Result) {
console.log("Step 1's result is: " + step1Result);
step2(step1Result, function(step2Result) {
console.log("Step 2's result is: " + step2Result);
})
});
// Output:
// Step 1's result is: Step 1 has these params{"hello":"there"}
// Step 2's result is: Step 2 params = "Step 1 has these params{\"hello\":\"there\"}"
Edited for formatting