先看一下代码,想想他的输出是什么
var Q = require('q'),
defer = Q.defer();
defer.promise.then(console.log);
defer.resolve('SECOND');
console.log('FIRST');
程序先输出SECOND呢还是先输出FIRST? 要理解这个问题,就必须清楚promise时钟异步执行。
根据Promise/A+ 规范,promise MUST fire their resolution or rejection function on the same turn of the event loop that they are created on.
因此我们可以肯定,传到then里面的函数只能在fire的下一轮执行。
所以,上面的代码会先打印FIRST, 然后打印SECOND.