I need to return a value from a Winjs promise, something like this:
getString() {
var str: string;
new WinJS.Promise((completed, error) => { Test.getAString(completed, error); })
.done((s: string) => str = s);
return str;
}
The problem is str always returns undefined, but s has a value (ie "test") which I get in debug mode.
Thanks in advance to help me.
The reason why the str
variable is undefined is because it is returned before the promise is fulfilled. I assume Test.getAString
is asynchronous. It takes a little time before it completes. So return str;
is executed before it is done.
A way to overcome this is to return the promise and, instead of handling the done
-function here, handle the fulfillment when getting the string.
So you get something like:
getString().then((s:string)=> do something with the string.. );
function getString(){
return new WinJS.Promise((completed, error) => {
Test.getAString(completed, error);
});
}