Manish Jangir
Manish Jangir

Reputation: 5437

Javascript Promise Wont Resolve

I've written the following code but its going to reject instead of resolve callback.

(function() {
  var restante = 0;
  'use strict';

  function wait() {
    return new Promise(function(done, reject) {
      setTimeout(function() {
        if (restante = 0) {
          done();
        } else {
          reject();
        }
      }, 2000);
    });
  }
  wait().
  then(function() {
    console.log("First Resolution");
  }).catch(function() {
    console.log("Error occured");
  });
})();

Why its going to reject every time?

Upvotes: 1

Views: 97

Answers (2)

Barry Michael Doyle
Barry Michael Doyle

Reputation: 10658

In your if statement it should be:

if (restante == 0) {
    done();
}

OR (Better practice)

if (restante === 0) {
    done();
}

Your full code will look like this:

(function() {
  var restante = 0;
  'use strict';

  function wait() {
    return new Promise(function(done, reject) {
      setTimeout(function() {
        if (restante == 0) {
          done();
        } else {
          reject();
        }
      }, 2000);
    });
  }
  wait().
  then(function() {
    console.log("First Resolution");
  }).catch(function() {
    console.log("Error occured");
  });
})();

Conditional statements require == (or ===) while assigning statements contain the single =.

Upvotes: 2

G0dsquad
G0dsquad

Reputation: 4435

You have an assignment instead of a comparison:

if (restante = 0)

Should be:

if (restante === 0)

https://jsfiddle.net/6nx92hhf/2/

Upvotes: 5

Related Questions