bluebird promisifyAll()然后()不与节点require一起工作
我第一次使用承诺,所以请忍受我。
基本上,我没有看到我的.then()
语句被调用的function。
当我调用tt()
,它是否正常工作。
当我调用t.tAsync()
,再次调用t()
。
但是,当我调用t.tAync().then(console.log);
这是我的节点模块:
'use strict'; var t = function(){ console.log('inside t()'); return 'j'; }; module.exports = { t: t };
这里是我的演示脚本:
'use strict'; require('should'); var Promise = require('bluebird'); var t = require('../src/t'); Promise.promisifyAll(t); /* Call t() once to demonstrate. Call tAsync() and see t() is called Call tAsync.then(fn), and then isn't called */ // this works as expected, calling t() console.log('calling t()...' + tt()); // this also works, calling t() t.tAsync(); // the then() statement isn't called t.tAsync().then(function(res){ // I expect this to be called console.log('HHHUUUZZZAAAHHH' + res); }); /* Keep the script running 5 seconds */ (function (i) { setTimeout(function () { console.log('finished program'); }, i * 1000) })(5);
这里是testing的输出:
inside t() calling t()...j inside t() inside t() finished program
您的then
子句永远不会被调用,因为tAsync
期望t
调用callback而不返回值。
promisifyAll
包装Node.JSasynchronousAPI的所以它包装的function需要符合Node.JScallback签名:
function t(callback) { callback(null, 'j'); }
但是,我怀疑根据你的代码,你不希望promiseifyAll
而是try()
或method()
:
function t() { return 'j'; } Promise.try(t).then(function(result) { console.log(result); });
要么
var t = Promise.method(function() { return 'j'; }); t().then(function(result) { console.log(result); });
对比上面的是Bluebird.js具体。 要使用通用的Promise来执行此操作,您可以采取以下两种方法之一:
使用Promise构造函数:
function t() { return new Promise(function(resolve, reject) { resolve('j'); }); } t().then(function(result) { console.log(result); });
或者,使用then
链接function:
function t() { return 'j'; } Promise.resolve() .then(t) .then(function(result) { console.log(result); });
我也无法理解“那么”是如何工作的。 下面的代码示例(只是为了了解stream程而创build)可以帮助您:
var Promise = require('bluebird'); function task1(callback) { setTimeout(function(){ console.log("taks1"); callback(null, "taks1"); }, 2000); } var taks1Async = Promise.promisify(task1); taks1Async().then(function(result) { console.log("Current task2, previous: " + result); return "task2"; }) .then(function(result) { console.log("Current task3, previous: " + result); return "task3"; }) .catch(function(e) { console.log("error: " + e); }); console.log("Finished");