猫鼬将findOne()结果分配给变量

我有一个功能:

function RetrieveCountryCode(countryName,callback) {
  Country.find({ name: countryName },function(err,country) {
    if (err) {
      callback(err,null);
    } else {
      callback(null,country.code);
    }
  });
}

我正在这样使用它:

//find a country code of a given country by user
var userCountryCode = null;
RetrieveCountryCode(country,countryCode) {
  if (err) {
    console.log(err);
  }
  userCountryCode = countryCode;
});
console.log("COUNTRY CODE");
console.log(userCountryCode);

*为函数指定的参数“国家/地区”来自html表单,已正确传递,我对此进行了检查。

我仍然在控制台中得到相同的响应:国家代码。我在做什么错...?

ganmazhememahuan 回答:猫鼬将findOne()结果分配给变量

正如Suleyman在评论中所说,这是由于节点的异步特性所致。代码流不符合您的期望。互联网上有很多关于节点的异步特性的教程,我建议您了解它们并进行实验,因为起初它不是很直观。

由于这个原因,console.log(userCountyCode)RetrieveCountryCode()完成工作之前就已执行。

解决方案是将console.log(userCountyCode) 放入回调中。

例如,如果我的收藏中包含:

> db.countries.find()
{ "_id" : ObjectId("5dc4fcee86c118c901a7de35"),"name" : "Australia","code" : "61","__v" : 0 }

使用您拥有的代码的修改版本:

var userCountryCode = null;
var country = 'Australia';

mongoose.connect(url,opts)

function RetrieveCountryCode(countryName,callback) {
  Country.findOne({ name: countryName },function(err,country) {
    if (err) {
      callback(err,null);
    } else {
      callback(null,country.code);
    }
  });
}

RetrieveCountryCode(country,countryCode) {
  if (err) {
    console.log(err);
  }
  userCountryCode = countryCode;
  console.log("COUNTRY CODE");
  console.log(userCountryCode);
});
console.log('xxx');

请注意,我根本没有更改RetrieveCountryCode函数的定义。我只是更改了调用方式,并在回调中移动了console.log 内。我改用console.log('xxx')来代替。

运行此代码输出:

xxx
COUNTRY CODE
61

请注意,xxx是在国家/地区代码之前打印的,因为它是在回调打印查询结果之前执行的。

最后,您的代码总是打印null,因为:

  1. 在查询填充变量内容之前就将其打印出来。
  2. 您没有在回调内打印变量内容。

注意:我将您代码中的find()更改为findOne()。我相信find()是您的错字。

本文链接:https://www.f2er.com/3142282.html

大家都在问