简体   繁体   中英

Async File Operations with Suspend in Node.js

I'm having a little trouble returning values using Suspend. I keep getting "undefined" (I am able to use the variable "files" from within the function - I just can't return it):

var fs = require('fs');
var recursive = require('recursive-readdir');
var suspend = require('suspend');

function foo () {}

foo.prototype.readfiles = suspend(function*() {
    var files = yield recursive('src', suspend.resume());
    return files;
});

foo.prototype.build = function() {
    console.log(this.readfiles()); //undefined 
    return this;
};

new foo()
    .build()

Thanks in advance for the help.

You're using suspend correctly, but not in conjunction with console.log(), which will fire asynchronously. Console.log() is not a generator function; it will not wait for the result of a yield statement. Instead, you need to explicitly call the console.log() statement after yield has returned a value.

Code below works to log out your files:

 var fs = require('fs'); var recursive = require('recursive-readdir'); var suspend = require('suspend'); function foo() {} foo.prototype.readfiles = suspend(function*() { var files = yield recursive('src', suspend.resume()); console.log(files) // prints out your files return files; }); foo.prototype.build = function() { // console.log(this.readfiles()); //undefined // return this; return this.readfiles(); }; new foo() .build() 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM