roger
roger

Reputation: 9893

node promise delay 10 sec then return itself?

I am using q to implement promise in my project, I want to do something like this:

  1. check if a >= 10, if so, then return;
  2. if not, call itself again.

my code is wrong, but it may help you understand me:

var Q = require("q");

function delay(ms) {
  var deferred = Q.defer();
  setTimeout(deferred.resolve, ms);
  return deferred.promise;
}

function wait(a) {
  var deferred = Q.defer();
  if (a >= 10) {
    deferred.resolve(a);
  } else {
    console.log("wait " + a);
    delay(10).then(wait(a + 1)).then(deferred.resolve(a));
  }

  return deferred.promise;
}

wait(1).then(console.log); // what I want is 10 instead of 1

Upvotes: 3

Views: 946

Answers (2)

Mike
Mike

Reputation: 3940

You just needed to wrap your delay 'then' function to resolve the 'write()' function's promise. You're currently resolving the promise from you're 'delay()' function as opposed to you're 'wait()' function, which is undefined. You're original code actually resolved the promise to the parameter 'a' which was one.

(I also changed the greater than comparison to be '>=')

var Q = require("q");

function delay(ms) {
  var deferred = Q.defer();
  setTimeout(deferred.resolve, ms);
  return deferred.promise;
}

function wait(a) {
  var deferred = Q.defer();
  if (a >= 10) {
    deferred.resolve(a);
  } else {
    console.log("wait " + a);

    // Resolve the promise from 'wait()' not 'delay()'
    // Promise resolution takes a function as a parameter and passes 
    // its resolution value as a parameter to that function.
    //
    // This logic resolves various promises in a stack. This logic
    // makes the final promise resolve when the terminating condition
    // 'a >= 10' is satisfied, and is returned to the original call.
    delay(10).then(wait(a + 1).then(function(result){deferred.resolve(result)});
  }

  return deferred.promise;
}

wait(1).then(console.log); // Result is automatically passed in as a parameter to 'console.log()'

Upvotes: 2

Aᴍɪʀ
Aᴍɪʀ

Reputation: 7803

You are resolving a in the function.

delay(10).then(wait(a + 1)).then(deferred.resolve(a));

As your first function call is wait(1), so a=1 and it resolves the result to be 1.

I changed a code a little bit.

You can see in the code, you have access to the resolved value in the function you put in .then. You should use that value, not the original a.

var Q = require("q");

function delay(ms) {
  var deferred = Q.defer();
  setTimeout(deferred.resolve, ms);
  return deferred.promise;
}


function wait(a) {
  var deferred = Q.defer();
  if (a >= 10) {
    deferred.resolve(a);
  } else {
    console.log("wait " + a);
    delay(10).then(function () {
        return wait(a + 1);
    }).then(function (data) {
        deferred.resolve(data);
    });
  }

  return deferred.promise;
}

wait(1).then(console.log); // what I want is 10 instead of 1

Upvotes: 3

Related Questions