在Q承诺中,为什么fcall被称为即时电视

In Q promises, why is fcall called immediatelly?

本文关键字:被称为 电视 fcall 为什么 承诺      更新时间:2023-09-26

拥有此代码

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中的任何函数。

所以,对于你的问题"我如何让函数只有在被调用之后才能被调用?",你不能,至少不能按照你想要的方式。这不是promise的工作方式。

但你当然可以这样做:

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);