Frage

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

War es hilfreich?

Lösung

It looks like you need to return your deferred object in promiseRead()

Andere Tipps

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();
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top