Reputation: 23
I'm having trouble figuring out how I could do sub functions and have a deferred function wait to call that before returning.
I've taken a sample and modified it. It shows what i'd like to do.
Basicly in the following example bingRequest calls sub which just sets a value. I'd like the BingRequest to wait till that sub call is completed. In my real world case that value effects what the bingRequest function would return. I've currently just got sub code stuck in the bingRequest but it makes for a very large function that would be cleaner if I could have the sub code split out. If I have to do it all combined I will but would like to be able to split some code out.
Thanks for taking a look.
<!DOCTYPE html>
<html >
<head>
<link rel="stylesheet" href="../../_static/js/dojo/../dijit/themes/claro/claro.css">
<script>dojoConfig = { async: true, parseOnLoad: false }</script>
<script src='//ajax.googleapis.com/ajax/libs/dojo/1.8.0/dojo/dojo.js'></script>
<script>
require(["dojo/promise/all", "dojo/Deferred", "dojo/dom", "dojo/on", "dojo/json", "dojo/domReady!"],
function (all, Deferred, dom, on, JSON) {
var y = "none"
function googleRequest() {
var deferred = new Deferred();
setTimeout(function () {
deferred.resolve("foo");
}, 500);
return deferred.promise;
}
function bingRequest() {
var deferred = new Deferred();
setTimeout(function () {
deferred.resolve("bar");
sub();
}, 750);
return deferred.promise;
}
function sub() {
setTimeout(function () {
y = "some";
}, 750)
}
function baiduRequest() {
var deferred = new Deferred();
setTimeout(function () {
deferred.resolve("baz");
}, 1000);
return deferred.promise;
}
on(dom.byId("startButton"), "click", function () {
dom.byId("output").innerHTML = "Running...";
all([googleRequest(), bingRequest(), baiduRequest()]).then(function (results) {
dom.byId("output").innerHTML = JSON.stringify(results)+y;
});
});
});
</script>
</head>
<body class="claro">
<h1>Output:</h1>
<pre id="output"></pre>
<button type="button" id="startButton">Start</button>
</body>
</html>
Upvotes: 2
Views: 1108
Reputation: 2698
If you are waiting for sub then you have to move the code to the sub function. also you must forfill the promise, i dont see that in your code
function sub() {
var deferred = new Deferred();
setTimeout(function () {
y = "some";
deferred.resolve(true);
}, 750)
return deferred.promise;
}
Also in the calling function you have to wait for the response using then.. CORRECTION moved the deffered.resolve("bar") to inside then.
function bingRequest() {
var deferred = new Deferred();
setTimeout(function () {
sub().then(function(ret){
//do what you want with y and return this promise
//ret will be the value you set in the resolve in this case true
deferred.resolve("bar");
});
}, 750);
return deferred.promise;
}
Fiddle:http://jsfiddle.net/theinnkeeper/pJXJ9/
Upvotes: 1