简体   繁体   English

Javascript承诺不等待解决

[英]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 . 我的印象是console.log调用将输出first second third ,但相反导致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());

}());

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM