这可能是一个菜鸟问题,但我是新的 promise ,并试图弄清楚如何使用 Q在 node.js 中。
我看到 tutorial以
开头promiseMeSomething()
.then(function (value) {}, function (reason) {});
但我无法掌握 .then
的确切来源。我猜它来自
var outputPromise = getInputPromise()
.then(function (input) {}, function (reason) {});
但是 getInputPromise()
是从哪里来的呢?我发现以前没有提到它。
我已经将它包含在我的项目中
var Q = require('q');
// this is suppose, the async function I want to use promise for
function async(cb) {
setTimeout(function () {
cb();
}, 5000);
}
async(function () {
console.log('async called back');
});
如何在我的示例中使用 Q
及其 .then
?
最佳答案
promiseMeSomething()
将返回一个 Q promise 对象,其中包含 then
函数,即 defined ,像这样
Promise.prototype.then = function (fulfilled, rejected, progressed) {
创建 Promise 对象的最简单方法是使用 Q
函数构造函数,如下所示
new Q(value)
将创建一个新的 Promise 对象。然后,您可以像这样附加成功和失败处理程序
new Q(value)
.then(function(/*Success handler*/){}, function(/*Failure handler*/){})
此外,如果您将单个 nodejs 样式的函数传递给 .then
函数,它将以这样的成功值调用该函数
callback(null, value)
或者如果有问题,那么
callback(error)
对于您的特定情况,setTimeout
接受要调用的函数作为第一个参数。因此,只需要几行代码就可以让它真正与 Promise 一起工作。所以,Q
有一个方便的功能,为此,Q.delay
,可以这样使用
var Q = require('q');
function async() {
return Q.delay(1000)
}
async()
.then(function() {
console.log('async called back');
});
你可以这样写更短
Q.delay(1000)
.then(function() {
console.log('async called back');
});
如果你想用其他值调用回调函数,那么你可以这样做
Q.delay(1000, "Success")
.then(function(value) {
console.log('async called back with', value);
});
当您希望在两个函数之间有延迟并且第二个函数依赖于第一个函数时,这将很有用。
关于javascript - 如何在 node.js 中实际使用 Q Promise?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22678613/