- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
我目前正在学习如何在 nodejs 中使用 Promise
所以我的第一个挑战是列出目录中的文件,然后使用异步函数通过两个步骤获取每个文件的内容。我提出了以下解决方案,但有一种强烈的感觉,这不是最优雅的方法,尤其是第一部分,我将异步方法“转换”为 Promise
// purpose is to get the contents of all files in a directory
// using the asynchronous methods fs.readdir() and fs.readFile()
// and chaining them via Promises using the bluebird promise library [1]
// [1] https://github.com/petkaantonov/bluebird
var Promise = require("bluebird");
var fs = require("fs");
var directory = "templates"
// turn fs.readdir() into a Promise
var getFiles = function(name) {
var promise = Promise.pending();
fs.readdir(directory, function(err, list) {
promise.fulfill(list)
})
return promise.promise;
}
// turn fs.readFile() into a Promise
var getContents = function(filename) {
var promise = Promise.pending();
fs.readFile(directory + "/" + filename, "utf8", function(err, content) {
promise.fulfill(content)
})
return promise.promise
}
现在链接两个 promise :
getFiles() // returns Promise for directory listing
.then(function(list) {
console.log("We got " + list)
console.log("Now reading those files\n")
// took me a while until i figured this out:
var listOfPromises = list.map(getContents)
return Promise.all(listOfPromises)
})
.then(function(content) {
console.log("so this is what we got: ", content)
})
正如我在上面所写的,它返回所需的结果,但我很确定有一种更优雅的方法。
最佳答案
使用 generic promisification 可以缩短代码和 .map
方法:
var Promise = require("bluebird");
var fs = Promise.promisifyAll(require("fs")); //This is most convenient way if it works for you
var directory = "templates";
var getFiles = function () {
return fs.readdirAsync(directory);
};
var getContent = function (filename) {
return fs.readFileAsync(directory + "/" + filename, "utf8");
};
getFiles().map(function (filename) {
return getContent(filename);
}).then(function (content) {
console.log("so this is what we got: ", content)
});
事实上,由于这些功能不再发挥作用,因此您可以进一步调整它:
var Promise = require("bluebird");
var fs = Promise.promisifyAll(require("fs")); //This is most convenient way if it works for you
var directory = "templates";
fs.readdirAsync(directory).map(function (filename) {
return fs.readFileAsync(directory + "/" + filename, "utf8");
}).then(function (content) {
console.log("so this is what we got: ", content)
});
.map
应该是你在使用集合时的基本方法 - 它真的很强大,因为它适用于任何事情,从一个 promise 到一系列 promise ,再到进一步 promise ,再到任何混合之间的直接值。
关于javascript - 与 fs 和 bluebird 的 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19429193/
bluebird.js和bluebird.core.js有什么区别? 什么时候应该使用bluebird.core.js而不是bluebird.js? 我无法在bluebird site或其他地方找到任
我正在从异步转换为 Bluebird,但不知道如何打破循环 这是我想要实现的目标: 循环数据数组。 对于每个项目,检查它是否存在于数据库中。 将一个项添加到数据库(第一个不存在的项),然后退出.eac
我试图用 .try(function(){}).catch(function(){}) 块返回一个 promise 。我的问题是由我的 promise 类型引起的。 deleteProcess
我正在尝试使用 bluebird 的 .return() 来扩展 promise 解析值方法。 目前我正在使用以下代码: doSomethingAsync() // assu
我刚刚开始使用 Promise 和 Bluebird。调试时我可以看到我的函数执行了两次: 首先我收到此错误:TypeError:未捕获错误:无法读取未定义的属性“then” 然后我看到函数再次执行,
我想测试数组的每个元素,直到满足条件,然后跳过其余的。这是我想出的代码,它似乎有效,但我不确定它是否真的安全或有意想不到的副作用。欢迎其他解决方案。 let buddyAdded = false; r
假设我有以下 node.js 代码 function foo() { return promiseOne().then(function(result) { return pr
假设我想在从数据库查找用户后同时发送电子邮件并向客户端推送通知,我可以这样写 User.findById(userId).exec() .then(() => sendMail()) .then(()
.call 方法的 Bluebird 文档有 code sample标记为“链接破折号或下划线方法”。 下面的代码片段中链接的 .then(_) 的用途是什么? var Promise = requi
是否有某种方法可以检索从上一个 then 回调返回的任何内容(或传递给初始 Promise.resolve()/resolve())? const p = Bluebird.resolve().the
我有以下代码。当 f2 没有抛出错误时,它工作正常。 如果有错误,它会生成一个Unhandled rejection Error。 重写代码以避免 Unhandled rejection Error
我有一个来自这篇文章的后续问题:Chaining Requests using BlueBird/ Request-Promise 我对 promise 很陌生,所以请原谅我的天真。我成功地实现了这段
我是 Bluebird 的新手,我正在尝试创建一个新用户,但 reject 函数没有按预期工作。 问题是它为我创建了用户,即使它启动了错误There nickname is already in us
我正在尝试实现剪刀石头布游戏的 CLI 版本。我正在使用查询器模块来处理 IO。我的主要功能如下所示: RockPaperScissors.prototype.gameLoop = function(
此代码运行正常: let promise; try { promise = parent(); //but I want: await parent(); await cont
在 promise 了 fs-extra 后,我知道我可以使用 then 来访问文件。我猜想有某种机制,在获取文件后,它知道要移动到 then 链中的下一个链接。然而,接下来的then我只是放置了一个
我有以下代码。它按预期工作,没有抛出未处理的拒绝错误。 p = new Promise (fulfill, reject) -> reject new Error 'some error' p.c
我期待 Bluebird forgotten return warning出现,但由于某种原因它不起作用。 A demo : const Bluebird = require('bluebird');
我正在使用 bluebird图书馆结束memcached . memcached.set('foo', 'bar', 10, function (err) { /* stuff */ }); 此函数不
我正在尝试如下使用 Bluebird 的协程: var p = require('bluebird'); //this should return a promise resolved to valu
我是一名优秀的程序员,十分优秀!