gpt4 book ai didi

javascript - 有没有办法在node-orm中以同步方式调用每个函数?

转载 作者:行者123 更新时间:2023-11-30 00:29:48 25 4
gpt4 key购买 nike

我对 node-orm2 的异步行为有疑问。我有这样的查询:

req.models.posts
.find(...)
.order('-whatever')
.each(doMagic) //Problem happens here
.filter(function(post) { ... })
.get(callback);

function doMagic(post, i) {

post.getMagic(function(err, magic) {
...
});
};

我的问题是,由于 post.getMagic() 内部发生的事情是异步的,我的回调函数在 doMagic 完成之前执行。检查 source code我确认这是正常行为,但由于这是一个快速应用程序,我的服务器响应错误信息。

我尝试使用 waitfor同步调用 getMagic,但没有成功。这可能是我所缺少的。有没有办法让 each 函数像同步 map 函数一样工作?

最佳答案

更改您的代码以获取帖子,一旦您使用 async.js 对其进行迭代,并在完成后发送响应。

类似于:

var async = require('async');

req.models.posts
.find(...)
.order('-whatever')
.each()
.filter(function(post) {...
})
.get(function(posts) {

//iterate over posts here
async.eachSeries(posts, function(file, callback) {
post.getMagic(function(err, magic) {

//here comes the magic

//and then callback to get next magic
callback();

});
}, function(err) {

//respond here

});

});

关于javascript - 有没有办法在node-orm中以同步方式调用每个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30052924/

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