gpt4 book ai didi

node.js - 异步并行和 promise 不起作用

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

我有以下两个片段:

1.这是我想要运行的单元:

health.checkHealth = function (req, res) {
async.parallel({
cassandra: function (callback) {
cassandraRepository.ping(callback);
},
kafka: function (callback) {
kafkaHelper.ping(callback);
},
vault: function (callback) {
vaultClient.health()
.then((isOk)=>{
callback(null, isOk)})
.catch(()=>
callback(null, false));
}
}, function (err, result) {
var response = {};
if (result.cassandra) {
response.cassandra = "OK";
} else {
response.cassandra = "Failed";
res.status(500);
}

if (result.kafka) {
response.kafka = "OK";
} else {
response.kafka = "Failed";
res.status(500);
}

if (result.vault) {
response.vault = "OK";
} else {
response.vault = "Failed";
res.status(500);
}

res.send(response);
})

}

2.这是检查单元的测试:

     describe('vault is avaliable', function () {
beforeEach(sinon.test(function () {
sinon.stub(vaultClient, "health").resolves(true);
}));

it('should return 200', sinon.test(function (done) {
var response = {
vault: "OK"
};

var req = {};
var res = {};
var spySend = res.send = sinon.spy();
var spyStatus = res.status = sinon.spy();

health.checkHealth(req, res);
expect(spySend.calledOnce).to.equal(true);
expect(spySend.calledWith(response));
expect(spyStatus.calledOnce).to.equal(false);
}));

});

我的问题是,当我调用 checkHealth 时,它会继续执行下一行 (expect(spySend.usedOnce).to.equal(true);),而无需等待VaultClient 的 promise 完成。 我需要做什么才能使预期仅在“checkHealth”运行后运行。

最佳答案

您不需要使用async - 您可以按照其他人的建议,通过Promise.all直接在代码中使用promise。

此处的代码使用 Bluebird 的 promisifyAll,但您也可以 convert the APIs to use promises你自己。

//.props is bluebird, you can `.all` with native promises too
Promise.props({
cassandra: cassandraRepository.pingAsync(); // created by promisifyAll
kafka: kafkaHelper.pingAsync(),
vault: vaultClient.health()
}).then(results => {
// access results.cassandra, results.kafka and results.vaule here
});

关于node.js - 异步并行和 promise 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38998912/

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