退货承诺和内容(可以很多)

时间:2017-03-22 15:54:21

标签: javascript node.js promise

我是node.js的新手,并试图绕过承诺。我试图从文件中读取内容,返回承诺和文件的内容。我到目前为止能够读取文件的内容并将其打印在我的控制台上,并返回一个承诺。我也希望返回文件的内容。

到目前为止,这是我的代码。

function() {
return fs.exists(listFile).then(function (exists) {
    if(exists) {
        return fs.readFile(listFile).then(function(response) {
            console.log(response.toString());
        }).catch(function(error) {
            console.error('failed to read from the file', error);
        });
    }
}).catch(function(err) {
    console.error('Error checking existence', err)
});
};

2 个答案:

答案 0 :(得分:1)

fs.readFile(listFile)返回一个promise。这就是为什么你可以链接" .then()"它背后的方法。目前还没有任何东西可以归还。此外,它将返回到您传递给" .then"的回调函数。在第二行。

要访问文件的内容,您需要使用文件内容调用另一个函数,然后将其打印到控制台。

function() {
return fs.exists(listFile).then(function (exists) {
    if(exists) {
        fs.readFile(listFile).then(function(response) {
            console.log(response.toString());
            handleFileContents(response.toString());
        }).catch(function(error) {
            console.error('failed to read from the file', error);
        });
    }
}).catch(function(err) {
    console.error('Error checking existence', err)
});
};

function handleFileContents(content) {
    // ... handling here
}

答案 1 :(得分:0)

您不能return文件内容本身,它们是异步检索的。您所能做的就是返回 内容的承诺

function readExistingFile(listFile) {
    return fs.exists(listFile).then(function (exists) {
        if (exists) {
            return fs.readFile(listFile).then(function(response) {
                var contents = response.toString();
                console.log(contents);
                return contents;
 //             ^^^^^^^^^^^^^^^^
            }).catch(function(error) {
                console.error('failed to read from the file', error);
                return "";
            });
        } else {
            return "";
        }
    }).catch(function(err) {
        console.error('Error checking existence', err)
        return "";
    });
}

一样使用它
readExistingFile("…").then(function(contentsOrEmpty) {
    console.log(contentsOrEmpty);
});

顺便说一下,using fs.exists like you did is an antipattern,它一般都被弃用了。省略它,只是从一个不存在的文件中捕获错误:

function readExistingFile(listFile) {
    return fs.readFile(listFile).then(function(response) {
        return response.toString();
    }, function(error) {
        if (error.code == "ENOENT") { // did not exist
            // …
        } else {
            console.error('failed to read from the file', error);
        }
        return "";
    });
}