It looks like you need to return your deferred object in promiseRead()
Understanding promises in javascript using when library
-
28-09-2022 - |
문제
I've been trying to wrap my head around asynchronous programming and the use of promises. To help understand them, I've written some trivial nested code, but have run into a snag.
Here's the code: http://pastebin.com/hBtk9vER Make sure you install when library (npm install)
var when = require('when');
function promise() {
console.log("Promise");
promiseRead().then(function(string) {
console.log("Inner promise");
console.log(string);
});
}
function promiseRead() {
console.log("PromiseRead");
return baz().then(function() {
console.log("Inner Read");
var deferred = when.defer();
setTimeout(function() {
deferred.resolve("Hello World");
}, 5000);
});
}
function baz() {
console.log("BAZ");
return when(true);
}
promise();
My problem is that console.log(string)
is undefined, when I was expecting it to be "Hello World"
after promiseRead()
resolves. Interestingly, when I remove the timeout, it works as expected. Can anybody help explain this, why the promise
function is executing it's code before promiseRead()
has finished timeout.
Much appreciated
해결책
다른 팁
some updates
var when = require('when');
function promise() {
console.log("Promise");
promiseRead().then(function(string) {
console.log("Inner promise");
console.log(string);
});
}
function promiseRead() {
console.log("PromiseRead");
return baz().then(function() {
console.log("Inner Read");
var deferred = when.defer();
setTimeout(function() {
deferred.resolve("Hello World");
}, 5000);
return deferred.promise;
});
}
function baz() {
console.log("BAZ");
return when(true);
}
promise();
제휴하지 않습니다 StackOverflow