medikoo / deferred

Modular and fast Promises implementation for JavaScript
ISC License
364 stars 20 forks source link

Promise resolving if initially initialized to false or null. #39

Closed ghost closed 9 years ago

ghost commented 9 years ago

Hello -

I have an issue with using multiple promises that need to be resolved in order, as each one depends on the value from the previous resolved promise. I figured I could get away with initially initializing a promise to false and then set it to an actual promise via a function invocation but that doesn't seem to work. For example:

var deferred = require('deferred');

function delay() {
  var def = deferred();

  setTimeout(function() {
    def.resolve('hello world!');
  }, 5000);

  return def.promise;
}

function delay2() {
  var def = deferred();

  setTimeout(function() {
    def.resolve('hello universe!');
  }, 5000);

  return def.promise;
}

var dPromise = delay();
var dPromise2 = null;

deferred(dPromise).then(function(result) {
  console.log(result);
  dPromise2 = delay2();
}).done();

deferred(dPromise2).then(function(result) {
  console.log(result);
}).done();

In the code above, the dPromise2 is null, however, the second thenable function is invoked immediately, printing "null" to the console. Same results if I initially set dPromsie2 to false.

I also tried initially setting dPromsie2 to deferred():

var dPromise2 = deferred();

This immediately printed the following to the console:

{ promise: [Function], resolve: [Function], reject: [Function] }

If I change my 2nd thenable to what I have below it will hang.

deferred(dPromise2.promise).then(function(result) {
  console.log(result);
}).done();

I can actually get this all working if I move the 2nd thenable into the first one but I'm trying to avoid this. I also looked into chaining but that did not seem to work either.

deferred(dPromise, dPromise2).then(function(result1, result2) {
  console.log(result2);
}).done();

As this will print:

hello world!
undefined

Thank you!

medikoo commented 9 years ago

@andrewschools from what you wrote, what you need is probably something as below:

var resultPromise = delay().then(function (delayResult) {
  return delay2(delayResult);
})(function (delay2Result) {
  return delay3(delay2Result);
});

resultPromise.done(function (delay3Result) {
  // Process final result of delay3 function
});

Let me know if that answers your question

ghost commented 9 years ago

@medikoo - Thank you. This helped a lot. I guess I really didn't understand the concept of chaining. Much appreciated!