What you don't understand is how the javascript compiler deals with promises.
This is how the compiler looks at your code;
var textFromElement = someElement.getText().then(function(text){return text})
var splittedText = textFromElement.split(" ")
1 - All variable are created at the top of the function scope regardless of where you assign it.
var textFromElement; (= undefined)
var splittedText; (= undefined)
2 - Does the minimum amount of work it can get away with for each line and moves to the next line.
testFromElement = {promise element object};
splittedText = {promise element object}.split(" "); (= undefined)//This what you don't want.
3 - Starts at the top and does more minimal work on unresolved lines.
testFromElement = {promise getText object};
4 - Starts at the top and does more minimal work on unresolved lines.
testFromElement = "text text";
In short it assigns splittedText three step before you want it to.
Good example:
var splittedText;
it("should get split text", function(done) {
someElement.getText().then(function(textFromElement){
splittedText = textFromElement.split(" ");
done();
})
})
1 - All variable are created at the top of the function scope regardless of where you assign it.
var splittedText; (= undefined)
2 - Only work is done inside this function until done() is called
it("should get split text", function(done) {
3 - Does the minimum amount of work it can get away with for each line and moves to the next line.
someElement = {promise element object};
4 - Starts at the top of the function and does more minimal work on unresolved lines.
someElement.getText() = {promise getText object};
5 - Starts at the top of the function and does more minimal work on unresolved lines.
textFromElement = "text text";
splittedText = textFromElement.split(" "); (["text","text"]);
done(); //the compiler can now to work outside this function