在 Q promises 中,为什么会立即调用 fall?
In Q promises, why is fcall called immediatelly?
有这个代码
var Q = require('q');
var first = Q.fcall(function() {
console.log('This will be output before actual resolution?');
return "This is the result.";
});
setTimeout(function() {
console.log('Gonna resolve.');
first.then(function(r) {
console.log(r);
});
}, 3000);
为什么结果是
This will be output before actual resolution?
Gonna resolve.
This is the result.
而不是
Gonna resolve.
This will be output before actual resolution?
This is the result.
如何让函数仅在 then
被调用后被调用?
您误解了(典型的 Javascript)承诺的工作方式。他们不会等到你给他们打电话.then
。他们做自己的工作,完成后,他们调用传递给 .then
的任何函数。
所以对于您的问题 "how do I make the function be called only after then was called?",您不能,至少不能按照您尝试的方式进行。这不是承诺的工作方式。
但你当然可以这样做:
var Q = require('q');
var getFirst = function () {
return Q.fcall(function() {
console.log('This will be output before actual resolution?');
return "This is the result.";
});
};
setTimeout(function() {
console.log('Gonna resolve.');
getFirst().then(function(r) {
console.log(r);
});
}, 3000);
有这个代码
var Q = require('q');
var first = Q.fcall(function() {
console.log('This will be output before actual resolution?');
return "This is the result.";
});
setTimeout(function() {
console.log('Gonna resolve.');
first.then(function(r) {
console.log(r);
});
}, 3000);
为什么结果是
This will be output before actual resolution?
Gonna resolve.
This is the result.
而不是
Gonna resolve.
This will be output before actual resolution?
This is the result.
如何让函数仅在 then
被调用后被调用?
您误解了(典型的 Javascript)承诺的工作方式。他们不会等到你给他们打电话.then
。他们做自己的工作,完成后,他们调用传递给 .then
的任何函数。
所以对于您的问题 "how do I make the function be called only after then was called?",您不能,至少不能按照您尝试的方式进行。这不是承诺的工作方式。
但你当然可以这样做:
var Q = require('q');
var getFirst = function () {
return Q.fcall(function() {
console.log('This will be output before actual resolution?');
return "This is the result.";
});
};
setTimeout(function() {
console.log('Gonna resolve.');
getFirst().then(function(r) {
console.log(r);
});
}, 3000);