gpt4 book ai didi

javascript - Node.js 使用 if 和异步调用控制流程

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

我正在将 Rails 代码移植到 Node.js,但遇到了控制流问题。移植以下代码的最佳方式应该是什么:

filter = {blah:blah};

result = {};

if(filters.something) {
asyncDBCall(function(){
result.something = somevalue;
});
}

if(filters.someOtherThing) {
asyncDBCall(function() {
result.someOtherThing = someothervalue;
});
}

return result;

最佳答案

Node JS 的主要优点和缺点是它在执行函数时的异步特性。你的代码应该是

if (filters.something) {
asyncDBCall(function() {
result.something = somevalue;
return result;
});
}

if (filters.someOtherThing) {
asyncDBCall(function() {
result.someOtherThing = somevalue;
return result;
});
}

但是如果两个条件都可能为真。在这种情况下,您必须等待另一个 asyncDBCall 完成才能进行下一个 asyncDBCall。代码将是

if (filters.something) {
asyncDBCall(function() {
result.something = somevalue;
if (filters.someOtherThing) {
asyncDBCall(function() {
result.someOtherThing = somevalue;
return result;
});
}
});
}

还有另一种解决方案,允许同时发送两个请求。

var someFlag = false, someOtherFlag = false;
if (filters.something) {
asyncDBCall(function() {
result.something = somevalue;
someFlag = true;
if (someFlag && someOtherFlag)
return result;
});
}

if (filters.someOtherThing) {
asyncDBCall(function() {
result.someOtherThing = somevalue;
someOtherFlag = true;
if (someFlag && someOtherFlag)
return result;
});
}

如果过滤器对象有很多属性,则需要使用递归。

关于javascript - Node.js 使用 if 和异步调用控制流程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24161447/

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