gpt4 book ai didi

javascript - 在 JavaScript 中启动另一个函数之前等待一个函数结束

转载 作者:行者123 更新时间:2023-11-30 10:31:28 26 4
gpt4 key购买 nike

我只是 JavaScript 的初学者,我想等待一个 Action 结束后再执行下一个 Action 。我已经在 Google 上搜索了我的问题的答案,但我发现的只是使用回调将函数串在一起。好的,但这不是我需要的。我不想做一个链条,我想做一个叠瓦,像这样:

function f1() {
function f2() {
function f3() {
return result;
}
return result;
}
return result;
}

因此,当我调用 console.log(f1) 时,它会打印在 f3() 中计算的结果。有没有一种简单的方法可以做到这一点?

谢谢。

萨拉。

编辑:好吧,我想我必须举一个更好的例子!具体来说,我在使用 express 的 Web 服务器和使用 mongoose 和 mongodb 的数据库上工作。我有四种类型的路径:关于工作、组、 worker 和用户的路径。当我获得一个页面时,我必须获得数据库中要显示的正确元素列表:如果我进入页面/job,我会得到现有工作的列表,如果我进入页面/user,我会得到现有用户列表等。在路由文件中,我调用另一个文件来管理与数据库的连接。这是我的代码:

在文件 route.js 中:

var mongo = require('./mongo');
exports.list = function(req, res) {
var data = mongo.read(req.params.type);//the type of element we are looking for (jobs, user...)
res.render('liste', {
table: data; //In the view, we get table.name, table.status, for each element of the table
}
}

在我的 mongo.js 中:

exports.read = function(type) {
var result;
start(); //It's the function which start the database, create the schemas, etc...
if(type == 'job')//4 conditions, in which we get the right model (in the var model) according to the page we're looking for
model.find(function(err, data) {
if(err) { ... }
else {
result = data;
}
}

return result; //It return nothing, because it do this before doing the model.find(...)
}

我希望它更清楚。

编辑(再次......):感谢大家的回答,感谢 Sagi Isha 给我解决方案:)

最佳答案

根据您的节点/表达代码:节点异步工作,这意味着您需要将回调传递给 I/O 操作,

var mongo = require('./mongo');
exports.list = function(req, res) {
mongo.read(req.params.type, function(err, data){
if (err) {return console.error(err)}
res.render('liste', {table: data});
});
}

exports.read = function(type, callback) {
if(type == 'job') {
model.find(callback);
}
}

关于javascript - 在 JavaScript 中启动另一个函数之前等待一个函数结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16708826/

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