私は JavaScript の初心者です。次のアクションを実行する前にアクションの終了を待ちたいと思います。Google で自分の問題に対する回答を既に検索しましたが、コールバックを使用して関数をつなぎ合わせる方法しか見つかりませんでした。わかりましたが、それは私が必要とするものではありません。私はチェーンを作りたくない、私はこのように刻印を作りたい:
function f1() {
function f2() {
function f3() {
return result;
}
return result;
}
return result;
}
そのため、console.log(f1) を呼び出すと、f3() で計算された結果が出力されます。これを行う簡単な方法はありますか?
ありがとうございました。
サラ。
編集:まあ、私はより良い例を挙げなければならないと思います! 具体的に言えば、私はエクスプレスを備えたWebサーバーと、mongooseとmongodbを備えたaaデータベースで作業しています。ジョブ、グループ、ワーカー、およびユーザーに関するパスの 4 種類のパスがあります。ページを取得したら、表示するデータベース内の要素の正しいリストを取得する必要があります。ページ /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(...)
}
より明確になることを願っています。
EDIT(再び...):皆さんの回答に感謝し、ソリューションを提供してくれたSagi Ishaに感謝します:)