我正在遵循来自 mongoDB js API 的代码示例,非常简单的代码示例:
const getAddressFromDB = async () => {
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
let res = []
let num = 0
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'addr';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
console.log("Connected correctly to db");
const db = client.db(dbName);
findDocuments(db, function(doc) {
client.close();
console.log(doc);
//return doc
res = doc
num = 1
});
});
const findDocuments = function(db, callback) {
// Get the documents collection
const collection = db.collection('documents');
// Find some documents
collection.find({}).toArray(function(err, docs) {
assert.equal(err, null);
//console.log("Found the following records");
//console.log(docs)
//docs.forEach(function(element){
// address.push(element.address)
//});
//res = docs
callback(docs);
});
}
if(num == 1){
return res
}
}
const helper = async() => {
let addressList = await getAddressFromDB()
console.log(addressList)
addressList.forEach(function(element){
console.log(element)
console.log("trying "+element.address)
checkBalanceAndSendTx(element.address,element.privateKey)
});
}
helper()
我试图从本地主机上的 mongoDB 获取文档,然后将该数组传递给 for each 循环并做一些事情,但是,我得到 TypeError: Cannot read property 'forEach' of undefined,命令的输出是这样的:
undefined
(node:6757) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'forEach' of undefined
at helper (/home/ubuntu/second/web3-node-tutorial/se.js:298:15)
at process._tickCallback (internal/process/next_tick.js:68:7)
at Function.Module.runMain (internal/modules/cjs/loader.js:721:11)
at startup (internal/bootstrap/node.js:228:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:576:3)
(node:6757) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:6757) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Connected correctly to db
[ { _id: 5b24b4e042ed9c0fed9d1f15,
address: '0x6FD04070704vvvC35194316a9033e10120',
privateKey: '0xc0ea45525dd0a04d6a0f8228czxc1807f6550948fde824d60167c37097c3' },
{ _id: 5b24b4e34257170ff8816e2c,
address: '0x45bCbe21basd830831a2783d620afFF549D5Ce',
privateKey: '0x520dbee37681a33d8c9180419c121d3c5sdfafde7ed3f750f7fc279f757c423' } ]
有人能指出为什么我在 getAddressFromDB() 中得到未定义的数组吗?我应该从 db 获取我想要的数组,因为我只在 num 为 1 时返回 res。
最佳答案
当您像使用 getAddressFromDB 一样等待一个函数时,该函数需要返回一个 promise 。在您的代码中,您将返回 undefined 因为您的 return 语句总是在数据库操作的回调执行完成之前执行。添加 async 不会改变这一点。
您可以通过定义一个 promise 并返回它来解决这个问题,就像这样(请参阅代码中的注释以获得进一步的解释):
// don't call require inside your function, it's common
// practice to do that at the beginning of your module
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const getAddressFromDB = () => {
// async functions need to return a promise,
// so we create one and and wrap everything in it
return new Promise(resolve => {
let res = []
let num = 0
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'addr';
// Use connect method to connect to the server
MongoClient.connect(url, function (err, client) {
assert.equal(null, err);
console.log("Connected correctly to db");
const db = client.db(dbName);
findDocuments(db, function (doc) {
client.close();
console.log(doc);
// this makes your promise ultimately resolve
// with the doc from MongoDB
resolve(doc);
});
});
const findDocuments = function (db, callback) {
// Get the documents collection
const collection = db.collection('documents');
// Find some documents
collection.find({}).toArray(function (err, docs) {
assert.equal(err, null);
callback(docs);
});
}
});
}
const helper = async () => {
let addressList = await getAddressFromDB()
console.log(addressList)
addressList.forEach(function (element) {
console.log(element)
console.log("trying " + element.address)
checkBalanceAndSendTx(element.address, element.privateKey)
});
}
helper()
关于javascript 未处理的 promise 拒绝警告 : TypeError: Cannot read property 'forEach' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50895140/
我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou
我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t
Rackup通过Rack的默认处理程序成功运行任何Rack应用程序。例如:classRackAppdefcall(environment)['200',{'Content-Type'=>'text/html'},["Helloworld"]]endendrunRackApp.new但是当最后一行更改为使用Rack的内置CGI处理程序时,rackup给出“NoMethodErrorat/undefinedmethod`call'fornil:NilClass”:Rack::Handler::CGI.runRackApp.newRack的其他内置处理程序也提出了同样的反对意见。例如Rack
我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer
我试图使用yard记录一些Ruby代码,尽管我所做的正是所描述的here或here#@param[Integer]thenumberoftrials(>=0)#@param[Float]successprobabilityineachtrialdefinitialize(n,p)#initialize...end虽然我仍然得到这个奇怪的错误@paramtaghasunknownparametername:the@paramtaghasunknownparametername:success然后生成的html看起来很奇怪。我称yard为:$yarddoc-mmarkdown我做错了什么?
在MRIRuby中我可以这样做:deftransferinternal_server=self.init_serverpid=forkdointernal_server.runend#Maketheserverprocessrunindependently.Process.detach(pid)internal_client=self.init_client#Dootherstuffwithconnectingtointernal_server...internal_client.post('somedata')ensure#KillserverProcess.kill('KILL',
我已经从我的命令行中获得了一切,所以我可以运行rubymyfile并且它可以正常工作。但是当我尝试从sublime中运行它时,我得到了undefinedmethod`require_relative'formain:Object有人知道我的sublime设置中缺少什么吗?我正在使用OSX并安装了rvm。 最佳答案 或者,您可以只使用“require”,它应该可以正常工作。我认为“require_relative”仅适用于ruby1.9+ 关于ruby-主要:Objectwhenrun
我花了三天的时间用头撞墙,试图弄清楚为什么简单的“rake”不能通过我的规范文件。如果您遇到这种情况:任何文件夹路径中都不要有空格!。严重地。事实上,从现在开始,您命名的任何内容都没有空格。这是我的控制台输出:(在/Users/*****/Desktop/LearningRuby/learn_ruby)$rake/Users/*******/Desktop/LearningRuby/learn_ruby/00_hello/hello_spec.rb:116:in`require':cannotloadsuchfile--hello(LoadError) 最佳
我正在使用active_admin,我在Rails3应用程序的应用程序中有一个目录管理,其中包含模型和页面的声明。时不时地我也有一个类,当那个类有一个常量时,就像这样:classFooBAR="bar"end然后,我在每个必须在我的Rails应用程序中重新加载一些代码的请求中收到此警告:/Users/pupeno/helloworld/app/admin/billing.rb:12:warning:alreadyinitializedconstantBAR知道发生了什么以及如何避免这些警告吗? 最佳答案 在纯Ruby中:classA
我已经像这样安装了一个新的Rails项目:$railsnewsite它执行并到达:bundleinstall但是当它似乎尝试安装依赖项时我得到了这个错误Gem::Ext::BuildError:ERROR:Failedtobuildgemnativeextension./System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/rubyextconf.rbcheckingforlibkern/OSAtomic.h...yescreatingMakefilemake"DESTDIR="cleanmake"DESTDIR="