Tag: promise

带有promise / async-await的callback上下文

我正在尝试使用ES7的asynchronous等待function,以避免在我的一些代码中的callback地狱。 我正在使用SQLite,我需要在callback的上下文中访问一个variables。 为了说明,这里是从sqlite3 npm模块: module.exports = function() { db.run("INSERT INTO foo …", function(err) { // err is null if insertion was successful console.log("inserted id:", this.lastID); }); }; 假设我创build了一个承诺运行上面的代码,我怎样才能访问this.lastID与asynchronous等待function? module.exports = async function() { try { await db.run("INSERT INTO foo …"); // How can I access the `this` context? } catch (err) { } };

什么是最好的方法使用Q承诺循环? 在迭代到下一个之前等待链完成

我有以下情况: var ids = [120, 121, 122, 123, 124] function dummyPromise(pause) { var deferred = Q.defer(); setTimeout(function() { console.log(pause); deferred.resolve(pause); }, pause); return deferred.promise; } for(var i = 0; i < ids.length; i++) { dummyPromise(ids[i]) .then(dummyPromise) .then(dummyPromise) .then(dummyPromise) .then(dummyPromise) .done(function(){ console.log('done') }) } 我想在迭代到下一个之前等待链完成。 什么是最好的方法来解决这个问题?

Node.js – Gunzip已读文件的asynchronous问题

相对较新的node.js和asynchronous的做法,到目前为止,我已经能够使用承诺阅读文件使用fs readFile,但我没有任何运气让zlib Gunzip工作。 用Coffeescript写作: promisifyRun(fs, 'readFile', filepath, 'utf-8') .then (file) -> promisifyRun(zlib, 'Gunzip', file) .then (data) -> console.log "HELLO" return data .catch respondError res promisfyRun是承诺一个单一的function(我没有写,但它的确工作)。 我已经成功地将它用于fs.readFile组件,如下所示: promisifyRun(fs, 'readFile', filepath, 'utf-8') .then (data) -> return data .catch respondError res 这工作得很好,它等待文件被打开,然后继续。 'data'包含文件的主体。 我认为它应该是一个非常合乎逻辑的扩展,将枪支组件纳入其中,但迄今为止这一直是一个挑战。 我看了几个npm gunzip模块。 看起来最有趣的是gunzip-或者zlib.Gunzip (我在这里尝试)。 这个特定情况的错误信息是: “未处理的拒绝错误:发送后无法设置标题”。 我认为这与已经完成的asynchronous性原因有关 更新 – 全堆栈跟踪: 未处理的拒绝错误:发送后无法设置标题。 ServerResponse.send(/ Users / […]

我应该在哪里抓住这个Promise MongoError?

我升级了我的mongoose,所以当然我开始得到这些: DeprecationWarning: Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html 所以我加了mongoose.Promise = global.Promise 。 都好。 除了…现在我得到这个人: (node:20760) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): MongoError: exception: Index with name: stampRoundedToNearestHour_1 already exists with different options (node:20760) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise […]

下面的代码等待forEach完成

我有一个包含各种数据的大型数组,以及一个对数组执行一些基本的但是耗时的分析的函数。 我使用forEach循环遍历数组。 如果条件满足,我希望函数返回一个特定的元素,否则使用Promises,因为函数可能需要大量的时间来完成: var analyzeData = function (arr) { return new Promise(function (resolve, reject) { var answer = false; arr.forEach(function (elm) { if (elm.foo == true) { answer = elm; } }); resolve(answer); }); } 我遇到的问题是,我怀疑在forEach循环完成之前, answer正在解决; 即在forEach循环可以完成检查每个元素的foo属性之前,函数parsing为answer ,默认为false。 有没有办法确保forEach循环之后的代码等待循环完成迭代,或者以其他方式循环访问数组?

你如何可选地处理Javascript承诺中的错误?

我正在使用node.js中的Promises(使用Q库)。 我已经将所有基于callback的代码移植到了Promise中,而且一切都很顺利。 但是,我似乎还有一个模式,我觉得这个模式似乎在继续执行。 我觉得可能有更好的方法来处理这个问题,但我并不确定是什么。 基本上,如果你有可能从asynchronous操作中得到一个错误,你可能会也可能不能在本地处理它。 例如,处理某种types的错误,并传播其余的。 在基于callback的代码中,我会做这样的事情: fs.readFile(path, 'utf-8', function (err, data) { if(err) { if(err.code == "ENOENT") { cb(null, null); //it's fine to return null and eat the error } else { cb(err, null); //this is probably not fine, so barf } return; } … }); 在基于Promise的代码中,这变成: return fs.readFile(path, 'utf-8').then( function(data) { … }, […]

promisify请求模块后如何正确使用putAsync

我在这里和那里search,结果没有发现有关蓝鸟的promisified请求的putAsync方法。 var request = require('request'); var Promise = require('bluebird'); Promise.promisifyAll(require("request")); request.putAsync({ uri: buApiUrl, headers: { 'content-type': 'application/json' }, body: JSON.stringify({ name: BU, workstations: formattedWorkStaions[BU] }) }).spread(function (response, body) { debugHelper.log(body); }).catch(function (err) { debugHelper.error(err); }); 以上是我的程序中的代码片段。 而且它不发送放置请求。 在使用postAsync的时候,如果会发送post请求成功。 任何人都可以解释为什么吗

如何使用Q将事件侦听器转换为承诺

大家好,我是新来的nodejs,我试图学习承诺。 我试图实现一种菜单,将根据用户input执行某些function。 以下是我正在使用的代码: var q = require('q'); var readline = require('readline-sync'); function createNewPreset(){ var deferred = q.defer(); var preset = { "name" : undefined, "unit" : undefined, "interval" : undefined, "files" : [], } deferred.resolve(preset); return deferred.promise; } function addPreset(){ console.log("adding"); var deferred = q.defer(); createNewPreset() .then(function(){ console.log("Gettind input in addPreset"); }) .then(getUserInput) .then(function(data){ console.log("Adding […]

在Promisecallback中调用meteor方法

我正在尝试使用这个NPM包:我的Meteor应用程序中的Gumroad-API 。 当我尝试在Promisecallback中执行Meteor方法调用(或集合插入)时,遇到服务器端的问题。 以下是我的两个Meteor方法的代码: Meteor.methods({ testMethod: () => { console.log('TEST METHOD RUN'); }, fetchGumroadData: () => { const Gumroad = Meteor.npmRequire('gumroad-api'); let gumroad = new Gumroad({ token: Meteor.settings.gumroadAccessKey }); Meteor.call('testMethod'); // runs fine gumroad.listSales('2014-12-04', '2099-12-04', 1).then((result) => { console.log('1'); // runs fine Meteor.call('testMethod'); // execution halts here w/o error msg console.log('2'); // this never runs […]

如何使用可以启动/停止的recursion函数编写应用程序

我有一个需要不断运行一个function的应用程序。 该函数返回一个承诺。 我希望应用程序一直等到承诺解决之后再次启动该function。 此外,我的应用程序需要一个start和stopfunction,使其开始运行该function,或分别停止它。 这里有一个简单的例子: class App { constructor() { this.running = false this.cycles = 0 } start() { this.running = true this._run() } stop() { this.running = false } _run() { Promise.resolve().then(() => { this.cycles++ }).then(() => { if (this.running) { this._run() } }) } } module.exports = App 我的问题是,当我使用这个, setTimeout似乎放弃了我。 例如,如果我运行这个: const App […]