Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript promises not waiting for resolve

I thought I had a decent understanding of promises, until I ran into a problem with a simplifed code snippet bellow. I was under the impression that the console.log calls would output first second third, but instead results in second third first.

Can someone explain why the second and third promises are able to continue on without waiting for the first.

var Q = require('q');

(function() {

  var Obj = function() {

    function first() {
      var deferred = Q.defer();

      setTimeout(function() {
        console.log('in the first')
        deferred.resolve();
      }, 200);

      return deferred.promise;
    }

    function second() {
      return Q.fcall(function() {
        console.log('in the second');
      })
    }

    function third() {
      return Q.fcall(function() {
        console.log('in the third');
      })
    }

    return {
      first:  first,
      second: second,
      third:  third
    }
  };

  var obj = Obj();
  obj.first()
    .then(obj.second())
    .then(obj.third());

}());
like image 576
chris Avatar asked Mar 04 '14 07:03

chris


People also ask

Does await wait for promise to resolve?

The await operator is used to wait for a Promise and get its fulfillment value. It can only be used inside an async function or a JavaScript module.

How do you force promise to resolve?

You can use the async/await syntax or call the . then() method on a promise to wait for it to resolve. Inside of functions marked with the async keyword, you can use await to wait for the promises to resolve before continuing to the next line of the function.

How do you wait for a promise in JavaScript?

The keyword await is used to wait for a Promise. It can only be used inside an async function. This keyword makes JavaScript wait until that promise settles and returns its result.

What happens if you dont resolve promise?

A promise is just an object with properties in Javascript. There's no magic to it. So failing to resolve or reject a promise just fails to ever change the state from "pending" to anything else. This doesn't cause any fundamental problem in Javascript because a promise is just a regular Javascript object.


1 Answers

You shouldn't be invoking the function, but pass the function, like this

  obj.first()
    .then(obj.second)
    .then(obj.third);

Output

in the first
in the second
in the third
like image 69
thefourtheye Avatar answered Oct 01 '22 00:10

thefourtheye