node.js:如何返回一个回调函数的值? [英] node.js: how to return a value of a callback function?

查看:265
本文介绍了node.js:如何返回一个回调函数的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码(无法正常工作):

I have the following code (that doesn't work as expected):

var express = require('express')
var app = express()
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/interviews';

app.get('/', function(req, res){
    var result = get_document(res);
    res.send( result // show the results of get document in the browser //)
    console.log("end");
});

app.listen(3000, function(req, res) {
    console.log("Listening on port 3000");
});

function get_document() {
  MongoClient.connect(url, function(err, db) {
    var col = db.collection('myinterviews');
    var data = col.find().toArray(function(err, docs) {
      db.close();
      return docs[0].name.toString(); // returns to the function that calls the callback
    });
  });
}

函数 get_document应该返回存储在 myinterviews中的文档采集。问题在于, return docs [0] ...行返回col.find(调用回调的函数),而不是app.get(...)中的变量 result。

The function 'get_document' is supposed to return the documents stored in 'myinterviews' collection. The problem is that the line 'return docs[0]...' returns to col.find (which is the function that called the callback) and not to variable 'result' inside app.get(...).

您知道如何使文档返回结果变量吗?

Do you know how to make the documents return to 'result' variable?

推荐答案

您的 get_document 函数异步运行。调用 MongoClient.connect()可能需要一些时间,因此无法立即返回。要返回您从数据库调用中获得的值,您必须将回调传递给 get_document 函数。所以它应该看起来像这样:

Your get_document function runs asynchronously. The call to MongoClient.connect() could take some time, so it can't return immediately. To return the value you're after from your database call, you'll have to pass a callback into the get_document function. So it should look something like this:

var express = require('express')
var app = express()
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/interviews';

app.get('/', function(req, res){
    var result = get_document(function(result) {
        res.send(result);
        console.log("end");
    });
});

app.listen(3000, function(req, res) {
    console.log("Listening on port 3000");
});

function get_document(done) {
  MongoClient.connect(url, function(err, db) {
    var col = db.collection('myinterviews');
    var data = col.find().toArray(function(err, docs) {
      db.close();
      done(docs[0].name.toString()); // returns to the function that calls the callback
    });
  });
}

这篇关于node.js:如何返回一个回调函数的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆