Some days ago I had a challenge for you about a code that had a bug.
The cause of this problem is related to how we use promises. If we use a promise in another promise we should return the promise all the time. In this way we can create a chain. Without this, the JavaScript will not wait our async code to end execute and will call our callback. It is recommended to use then when we have intermediate stage of operation and done for the final call (we cannot have something like .done().done()).
To have a more readable code it is recommended to have calls to functions in a done or in a then and not a definition of a method. In this way any person will be able to read our code more easily.
var bingUrl = new Windows.Foundation.Uri("http://www.bing.com");
Windows.Storage.ApplicationData.current.temporaryFolder.createFileAsync("myFile.txt")
.then(function (myFile) {
var backgroundDownloader = new Windows.Networking.BackgroundTransfer.BackgroundDownloader();
var currentDownload = backgroundDownloader.createDownload(bingUrl, myFile);
currentDownload.startAsync();
})
.then(
function (result) {
return displayOkayStatus(result);
});
...
function displayOkayStatus(result){
return "Complete" + result.toString();
}
In the following code the result parameter from displayOkayStatus is undefined all the time.The cause of this problem is related to how we use promises. If we use a promise in another promise we should return the promise all the time. In this way we can create a chain. Without this, the JavaScript will not wait our async code to end execute and will call our callback. It is recommended to use then when we have intermediate stage of operation and done for the final call (we cannot have something like .done().done()).
To have a more readable code it is recommended to have calls to functions in a done or in a then and not a definition of a method. In this way any person will be able to read our code more easily.
var bingUrl = new Windows.Foundation.Uri("http://www.bing.com");
Windows.Storage.ApplicationData.current.temporaryFolder.createFileAsync("myFile.txt")
.then(function (myFile) {
var backgroundDownloader = new Windows.Networking.BackgroundTransfer.BackgroundDownloader();
var currentDownload = backgroundDownloader.createDownload(bingUrl, myFile);
return currentDownload.startAsync();
})
.then(
function (result) {
return displayOkayStatus(result);
});
...
function displayOkayStatus(result){
return "Complete" + result.toString();
}
Comments
Post a Comment