gpt4 book ai didi

node.js - bluebird promisifyAll() 和 then() 不与 Node require 一起使用

转载 作者:太空宇宙 更新时间:2023-11-03 23:33:40 25 4
gpt4 key购买 nike

我是第一次使用 Promise,所以请耐心等待。

基本上,我没有看到 .then() 语句中的函数被调用。

当我调用t.t()时,它是否正常工作。

当我调用 t.tAsync() 时,t() 再次被调用。

但是,当我调用 t.tAync().then(console.log); 时,结果并未传递到 then 中

这是我的 Node 模块:

'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()...' + t.t());

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

这是测试的输出:

inside t()
calling t()...j
inside t()
inside t()
finished program

最佳答案

您的 then 子句永远不会被调用,因为 tAsync 期望 t 调用回调而不返回值。

promisifyAll 包装 Node.JS 异步 API,因此它包装的函数需要符合 Node.JS 回调签名:

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 t() {
return 'j';
}

Promise.resolve()
.then(t)
.then(function(result) {
console.log(result);
});

关于node.js - bluebird promisifyAll() 和 then() 不与 Node require 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35234556/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com