简体   繁体   English

Promise无法在node.js上解决

[英]Promise isn't resolving on node.js

I'm having a lot of problems with node.js/Promises at the moment. 目前,我在使用node.js / Promises时遇到很多问题。 Currently I'm doing something simple as this: 目前,我正在做一些简单的事情,如下所示:

module.js module.js

var fs = require('fs');

function myFunction() {
    var files = []; 
    for (var i = 0; i < 100; ++i) {
        files.push(fs.writeFile("file-" + i + ".txt", "file" + i, "utf-8", function(err) {
            if (err)
                throw err;
        }));
    }
    Promise.all(files).then(function() {
        return new Promise(function(resolve, reject) {
            resolve('ok');
        })
    });
}
exports.myFunction = myFunction;

main.js main.js

var test = require('./module.js');

test.myFunction().then(function(result) {
    console.log(result);
})

Yet, my output if I run my main.js is: 但是,如果运行main.js,我的输出是:

module.myFunction().then(function(result) {
                   ^

TypeError: Cannot read property 'then' of undefined

I don't know why my module is returning a Promise as undefined. 我不知道为什么我的模块返回未定义的Promise。 Can anybody help me out here? 有人可以帮我吗? I just can't wrap my head around this. 我只是无法解决这个问题。 Thank you very much! 非常感谢你!

And, while writeFile() writes the files as file-0.txt and so on, the files have no content at all. 而且,虽然writeFile()将文件写为file-0.txt等,但这些文件根本没有内容。

You code has two problems: 您的代码有两个问题:

  • the native fs.writeFile() does not return a promise 本机fs.writeFile()不返回承诺
  • your function does not return a promise 您的函数没有返回承诺

For the first problem you can either code some wrapper yourself or use something like fs-promise . 对于第一个问题,您可以自己编写一些包装器,也可以使用fs-promise类的东西。 For the second problem you really need your function to return a promise for all the files. 对于第二个问题,您确实需要函数为所有文件返回promise。

Then your code could look like this: 然后您的代码可能如下所示:

var fsp = require('fs-promise');

function myFunction() {
  var files = []; 
  for (var i = 0; i < 100; ++i) {
    files.push( fsp.writeFile("file-" + i + ".txt", "file" + i, "utf-8" ) );
  }

  return Promise.all( files );

}
exports.myFunction = myFunction;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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