Tag: co

Koa中的协程和发生器之间的区别?

Coroutines和Generators之间的区别对我来说是模糊的。 我会很感激,如果有人可以阅读文章callbackvs协程 – 看看callbackVS发电机vs协程 “ 在https://medium.com/code-adventures/174f1fe66127 …然后解释在这篇文章中说明/展示了发生器和协程之间的区别和竞争(标题中是否使用了“vs”)? 更一般地说,我的问题是这个区别究竟是什么,这种区分是否适用于在Koa中构build应用程序时(在Node.js中)如何区别处理asynchronous请求的编码模式?

NodeJS / Express中的同步像编程一样

我很难与节点asynchronous操作(来自PHP背景)。 我知道你可以嵌套callback,但可以很快失控。 这是我想要同步解决的一个基本示例(我知道这个示例可能很简单,但是我需要知道如何同步执行更复杂的项目)。 这是一个快速的应用程序,我试图计算优惠券已被使用的次数: var express = require('express'); var wrap = require('co-express'); app.post('/grab-valid-coupons', wrap(function* (req, res) { var validCoupons = []; console.log('grabbing coupons'); var coupons = yield db.collection('Coupons').find({}).toArray(); coupons.forEach(wrap(function* (coupon, index) { console.log(coupon.code, 'CODE'); var couponUse = 0; couponUse += yield db.collection('Rentals').find({coupon: coupon.code}).count(); couponUse += yield db.collection('Orders').find({coupon: coupon.code}).count(); console.log(couponUse); if(couponUse < coupon.uses) { validCoupons.push(coupon); } […]

如何获得与koa thunk readStream?

我想在koa控制器中发出请求,这是工作: var s = require('through2')(); var req = http.request(url, function(res) { res.pipe(s); }) req.end(null); s.on('close', function() { console.log('has close'); }); this.body = s; 但与thunk,这似乎是行不通的。 var s = stream(); yield thunk(url, s); this.body = s; 这里是thunk : var thunk = function (url, s) { return function(callback) { var req = http.request(url, function(res) { res.pipe(s); }); s.on('close', […]

将带有callback的常规node.js函数转换为生成器和yield

我是koa.js的新手,非常喜欢它,并且开始了一个项目。 我需要使用twilio发送短信。 大多数要求twilio包裹遵循这个结构。 public.get('/najam', function *(){ this.body = "hello from najam"; //yeild before c.sendSms or inside callback? c.sendSms({ to:'YOUR_PHONE', }, function(e, m) { if (!e) { //yeild here? } }); }); 我怎么修改它把它放在发电机function,在什么时候我会使用yield关键字? 如果你的答案build议使用Co库,请给我提供代码和位解释的例子。

如何使用Node.js上的co模块捕获exception?

我在帆框架上使用co模块进行编码。 我想捕获InvalidError,但错误日志说'未定义'。 我怎样才能解决这个代码? Co模块不能捕获ErrorType规范? detail: function (req, res) { co(function *() { let errors = []; const text = req.param('text'); if (text.length <= 0) { throw new InvalidError('text is required'); } }).catch((InvalidError, err) => { sails.log.warn(err); errors.push(err.message); req.flash('errors', errors); res.redirect('/somewhere/view'); }).catch((Error, err) => { sails.log.error(err); res.serverError(err); }); } 错误日志在这里 warn: undefined error: undefined error: Sending […]

dynamic路线在科阿?

比方说,我有一个看起来像这样的路线数组: var routes = [ { route: '/', handler: function* () { this.body = yield render('home', template.home) } }, { route: '/about', handler: function* () { this.body = yield render('about', template.about) } } ]; 什么是最好的方式来app.use它们? 我尝试过这样做(用koa-route作为我的中间件): Promise.each(routes, function(r) { app.use(route.get(r.route, r.handler)); }).then(function() { app.use(function *NotFound(next) { this.status = 404; this.body = 'not found'; }); }); […]

在使用ES6类和生成器函数时,如何避免使用`self = this`这个hack?

我试图使用明确的.bind(这),并没有工作。 我也知道箭头function不在这里工作。 'use strict'; const co = require('co'); class ServiceDemo { constructor(repository, config, loggingService) { this.config = config; this.repository = repository; this.loggingService = loggingService; } checkForNotifications(pricePoint) { const self = this; return co(function*() { self.loggingService.debug('test'); //const surprisesToNotify = yield this.getSomething(pricePoint); }); } getSomething(){ return co(function*() { return {}; }); } } module.exports = SurpriseSchedulerService;

承诺与mongoose和es6不按预期工作

我有下面的代码创build一个承诺数组来保存一些数字,然后它产生的承诺(使用共库),并打印出结果。 但是,我不明白的是,当它打印输出时,会打印相同的logging10次。 这里是代码: 'use strict' const Promise = require('bluebird'); const co = require('co'); const _ = require('lodash'); const mongoose = require('mongoose'); // plug in the bluebird promise library for mongoose mongoose.Promise = Promise; mongoose.connect('mongodb://localhost:27017/nodejs_testing'); const numSchema = new mongoose.Schema({ num: { type: Number, required: true } }); const Num = mongoose.model('Num', numSchema); let promises = […]

为什么thunkify / yield总是返回一个数组?

我有一个名为logInline的thunk (从Co文档改编而来)。 我注意到thunkified get似乎总是yield一个数组。 这是由devise? 这是做这件事,或者它是yield的标准部分? var co = require('co'), get = thunkify(request.get); var logInline = co(function *(){ var google = yield get('http://google.com'); console.log(google[0].statusCode); }) logInline() 注意这里的variables“google”总是一个数组。 为什么? 请注意, request.get通常返回err, response (即没有数组)。 该脚本,BTW,返回200或任何其他响应代码google.com返回。 唉产量文件是相当稀疏的ATM。 编辑: Thunk不总是返回数组。 例如,如果var readFile = thunkify(fs.readFile); : var fileContents = yield readFile('myfile', 'utf8'); log(fileContents); 在这种情况下,fileContents不会在数组中返回。 那么为什么谷歌里面的数组? thunkify似乎有什么东西来控制thunk的回报

Console.log显示数组,但无法返回

我是新的承诺(我在节点中使用'co'),所以我不完全确定什么是失败的代码: function* excelToJSON(excelFileNames) { var jsonData = []; for (let index = 0; index < excelFileNames.length; index++) { parseXlsx(excelFilesNames[index], function (err, data) { jsonData.push(data); console.log(jsonData); //***Shows data correctly }); } console.log(jsonData); //***Empty array return yield jsonData; } 它读取文件,将其转换,至less在循环内,它显示正确的一切,但一旦我们走出循环的数据似乎消失。 我也试图从循环内返回一个值,但是这也不起作用。 编辑:parseXlsx是从'excel'模块在这里: https : //github.com/trevordixon/excel.js我不完全确定,如果是asynchronous或同步,说实话。 这似乎是它的代码,我知道'extractFiles'返回一个承诺,但因为它然后通过'parseXlsx'我不知道以后会发生什么: function parseXlsx(path, sheet, cb) { if (typeof cb === 'undefined') { […]