Tag: 承诺

使用node.js,stream和承诺下载文件

这是我的代码片段: var processListing = function (directoryItems) { console.log('foreach'); var itemsToDownload = []; directoryItems.forEach(function (element, index, array) { //Ignore directories if (element.type === 'd') { console.log('directory ' + element.name); return; } //Ignore non zips if (path.extname(element.name) !== '.zip') { console.log('ignoring ' + element.name); return; } //Download zip itemsToDownload.push({ source: element.name, destination: element.name }); //aftpSystem.downloadFile(element.name, element.name); }); […]

在使用Promise时挂在variables上的最佳做法

我对诺言是新的,我想知道什么最好的做法是保持variables,而下链? 通过Promise连接到MongoDB非常简单: connectToMongoDB(data).done(function(db) { var collection = db.collection('test_inserts'); // do more stuff here }); 但是如果我必须连接到两个不同的数据库会发生什么? connectToMongoDB1(data1).then(function(db1) { return connectToMongoDB2(data2); }).done(function(db2) { var collection = db1.collection('test_inserts'); // ERROR: db1 is undefined }); 那个错误非常有意义。 但是,如何转发db1而不改变我的connectToMongoDB2()函数,因为我想保持connectToMongoDB2()和所有我的承诺一般非常通用? 我的意思是,我可以围绕一个对象存储所有相关的东西,但是这看起来有点怪异: var relevantStuff = {}; connectToMongoDB1(data1).then(function(db1) { relevantStuff.db1 = db1; return connectToMongoDB2(data2); }).done(function(db2) { var collection = relevantStuff.db1.collection('test_inserts'); // do more stuff […]

断言在摩卡testing中打破asynchronousfunction

我正在构build一个节点模块,并试图尽我所能对它进行unit testing。 我已经设置了摩卡和柴做testing处理。 我有一个问题,testing我的asynchronous方法(返回承诺的方法)。 在下面的testing中,我正在testing一个“升级”对象的方法。 it('Should return a list of versions for the default git repo', function (done) { fs.writeFileSync(appSetup.CONFIG_FILENAME, JSON.stringify(appSetup.DEFAULT_CONFIG)); var upgrade = new Upgrade({ quiet: true }); upgrade.getVersions().then(function (versions) { assert(versions && versions.length > 0, 'Should have at least one version.'); assert.equal(1, 2); // this throws the exception which causes the test case […]

如何避免在JavaScript应用程序中丢失“this”上下文?

这是我的代码示例: function QueueService() { var key = Config.get("AWS.accessKeyID"); var secret = Config.get("AWS.secretKey"); var credentials = new AWS.Credentials(key, secret, sessionToken = null); this._sqs = new Promise.promisifyAll(new AWS.SQS({apiVersion: '2012-11-05', region: "us-west-2", endpoint: "sqs.us-west-2.amazonaws.com", credentials: credentials})); } QueueService.prototype.FillBirdQueue = function(birds) { var self = this; birds.forEach(function(bird_batch) { var params = { Entries: bird_batch, QueueUrl: Config.get("AWS-Queue.Birds") }; return self._sqs.sendMessageBatchAsync(params); […]

从asynchronous获取蓝鸟承诺等待function

我正在寻找一种方法,使用Node v7.6或更高版本,在调用asynchronous函数时获取Bluebird Promise(或任何非本地promise)。 我可以这样做: global.Promise = require('Bluebird'); // Or Q/When var getResolvedPromise = () => Promise.resolve('value'); getResolvedPromise .tap(…) // Bluebird method .then(…); 请参阅: 我可以使用global.Promise = require(“bluebird”) 我希望能够做到这样的事情: global.Promise = require('Bluebird'); // Or Q/When var getResolvedAsyncAwaitPromise = async () => 'value'; getResolvedAsyncAwaitPromise() .tap(…) // Error ! Native Promises does not have `.tap(…)` .then(…); 我知道我可以随时使用这样的东西: Bluebird.resolve(getResolvedAsyncAwaitPromise()) .tap(…); […]

包裹在承诺的JavaScript通用函数

如何将可以同步/同步function的函数封装在promise中? 我已经打电话给如下function action[fn](req, res); 在函数fn(在下面的例子中)可以在里面(我使用dynamic调用每个函数)同步或者像下面那样的同步, 它如何推荐包装在承诺。 如何处理错误,如果有… 我使用nodeJS应用程序 run: function (req, res, filePath) { var writeStream = fs.createWriteStream(fileRelPath, {flags: 'w'}); req.pipe(writeStream); req.on("end", function () { console.log("Finish to update data file") }); res.end("File " + filePath + " saved successfully"); }

Promise连接添加新的函数调用链

我试图加载和parsing一个文件,但是在调用两个函数时遇到了一些麻烦,并且返回了这个promise的结果。 我正在使用蓝鸟承诺。 以下代码按预期工作: run = function (filePath) { return Promise.join( fs.readFileAsync(filePath, 'utf8') .then(parseFile.parse.bind(null, 'userKey')), users.getUsersAsync(usersObj) .then(users.modifyRec.bind(null, process.env.users)) ).then(function (args) { return runProc('run', args[0], args[1]); …. 我已经将parseFile.parse函数分为两个方法, parseFile.parse和parseFile.getProp 。 parseFile.getProp应该从parseFile.parse获取输出,并返回在方法分解之前返回的parseFile.parse 。 这是我尝试使用这两个函数: run = function (filePath) { return Promise.join( fs.readFileAsync(filePath, 'utf8') .then(parseFile.parse.bind(null, 'userKey')) .then(parseFile.getProp.bind(null,'key')), users.getUsersAsync(usersObj) .then(users.modifyRec.bind(null, process.env.users)) ).then(function (args) { return runProc('run', args[0], args[1]); …. 但它不工作。 […]

在promisecallback中访问“this”的对象(然后)

我想用Javascript创build一个对象。 其中一种方法应该执行承诺链。 链中的每个方法都必须访问作为对象成员的configurationvariables。 问题是, this运算符在PromiseMethod2被改变,我无法访问configurationvariables(它在PromiseMethod1正常PromiseMethod1 )。 这是我的代码: var SomeObject(config) { var that = this; that.config = config; } SomeObject.prototype.SomeMethod = function() { var that = this; that.PromiseMethod1() .then(that.PromiseMethod2) .catch(console.error); } SomeObject.prototype.PromiseMethod1 = function() { var that = this; config = that.config; return SomePromise(); } SomeObject.prototype.PromiseMethod2 = function(someParams) { var that = this; config = that.config; […]

如何正确链接承诺与嵌套

我的节点项目目前包含一个嵌套callback的横向圣诞树,以获取数据并按正确的顺序处理它们。 现在我试图重构使用承诺,但我不确定如何正确地做到这一点。 比方说,我要提取一个办公室的名单,然后为每个办公室的所有员工,然后每个员工的工资。 最后,所有的实体(办公室,员工和工资)都应该连在一起并存储在一个数据库中。 一些说明我当前代码的伪代码(省略了error handling): fetch(officesEndpoint, function (data, response) { parse(data, function (err, offices) { offices.forEach(function (office) { save(office); fetch(employeesEndPoint, function (data, response) { parse(data, function (err, employees) { // link each employee to office save(office); save(employee); employees.forEach(function () { fetch(salaryEndpoint, function (data, response) { parse(data, function (err, salaries) { // link salary to […]

我怎样才能同步使用readline?

我只是试图等待用户input密码,然后使用它,然后继续我的代码的其余部分。 错误是Cannot read property 'then' of undefined 。 let rl = readline.createInterface({ input: process.stdin, output: process.stdout }); rl.question('Password: ', password => { rl.close(); return decrypt(password); }).then(data =>{ console.log(data); }); function decrypt( password ) { return new Promise((resolve) => { //do stuff resolve(data); }); }