NodeJS 在继续之前等待函数返回
只是在使用 NodeJS 构建函数时遇到一些问题。它似乎没有返回值,我有一种感觉,这是由于函数调用的异步性质造成的。任何帮助将非常感激!
sendFilesToDB 发送要处理的文件数组(来自 fs.readdir)。文件的内容用于构建 SQL 查询。成功插入后,该文件将被删除。但 fileToQuery 函数根本不返回字符串(给出“参数必须是字符串”错误)。
Just having some issues with building a function using nodeJS. It doesn't seem to be returning the value, and I have a feeling its due to the asynchronous nature of the function call. Any help would be really appreciated!
sendFilesToDB is sent an array (from fs.readdir) of files to be processed. The files' content is used to construct a SQL query. Once successfully inserted, the file is deleted. But the fileToQuery function does not return a string at all (gives a 'Argument must be a string' error).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
fileToQuery
返回 void,因为它说:您拥有的 return 语句不是从
filesToQuery
返回,而是从您定义它的匿名函数返回。您需要重写您的 < code>fileToQuery 函数接受一个额外的参数(可能是
resultCallback
),而不是返回你的 sql 字符串,你可以这样做:然后你将这样调用它:
顺便说一句:这是称为“连续传递样式”,可以用任何支持匿名函数的语言来完成。您所要求的称为可调用延续,但并不是很多语言都有它们。如果您有兴趣了解它们,您应该尝试选择方案。
fileToQuery
is returning void, because it says:That return statement you have isn't returning from
filesToQuery
but from the anonymous function you defined it in.You need to rewrite your
fileToQuery
function to take an extra argument (perhapsresultCallback
) and instead of returning your sql string, you do:You'll then call it like this:
By the way: This is called "continuation passing style" and can be done in any language that supports anonymous functions. What you asked for is called a callable continuation, but not very many languages have them. If you're interested in learning about them you should try picking up scheme.