标签: bluebird

复合let/const赋值是什么意思?

在Bluebird图书馆的wiki中有一篇文章优化杀手.在本文中有一个短语:

目前不可优化:
...
包含复合的
函数let赋值包含复合const赋值的函数

复合赋值和复合const赋值是什么意思?在ECMAScript 5.1中有复合赋值的概念,但在ECMAScript 2015中,似乎没有任何复合赋值的概念,只有常规赋值.

我怀疑复合let和const赋值,它只是声明后的复合赋值.例如:

let n = 1;
n += 4;
Run Code Online (Sandbox Code Playgroud)

我对吗?

javascript compound-assignment bluebird

24
推荐指数
1
解决办法
3328
查看次数

是否需要在承诺范围内嵌套捕获?

我们希望减少承诺中的捕获块数量.如果我们删除嵌套的catch,那么异常会冒泡到父catch吗?

temporaryUserModel.findOne({email: req.body.email})
    .then(tempUser => {
        if (tempUser) {
            temporaryUserModel.findOneAndUpdate({_id: tempUser.toJSON()._id}, user)
                .then((doc) => {
                    return res.status(200).json({
                        status: 'Success',
                        data: {url: planOpted.chargifySignupUrl}
                    });
                })
                .catch(err => error(err, res));
        } else {
            temporaryUserModel(user).save()
                .then((doc) => {
                    return res.status(200).json({
                        status: 'Success',
                        data: {url: planOpted.chargifySignupUrl}
                    });
                })
                .catch(err => error(err, res));
        }
    })
    .catch(err => error(err, res));
Run Code Online (Sandbox Code Playgroud)

我们想要移除两个嵌套的捕获并仅保留底部的捕获.这个可以吗?

javascript mongoose promise bluebird

23
推荐指数
2
解决办法
6193
查看次数

如何处理承诺错误?

作为节点程序员.我习惯使用"nodebacks"来处理我的代码中的错误:

myFn(param, function(err, data) {
    if (err){
        //error handling logic
     }
     else {
        // business logic
    }
});
Run Code Online (Sandbox Code Playgroud)

在编写该函数时,我可以执行以下操作:

var myFn = function(param, callback){
    var calc = doSomeCalculation(param);
    if(calc === null) { // or some other way to detect error
        callback(new Error("error with calculation"), null);
    }
    ...
    someAsyncOp(calcN,function(err, finalResult){
        if(err) return callback(err, null);
        callback(null, finalResult); // the error is null to signal no error
    });

};
Run Code Online (Sandbox Code Playgroud)

我如何使用promises进行这种错误处理?

javascript error-handling node.js promise bluebird

22
推荐指数
1
解决办法
4万
查看次数

我可以通过bluebird在节点全局范围内的实现来覆盖ES6的Promise吗?

我想使用bluebird实现Promise/A +开放标准并覆盖原生ES6 Promises.我还希望bluebird实现在我随后导入的模块中随处可用,而不必在每个模块中都需要它.Bluebird的入门页面告诉我:

var Promise = require("bluebird");
Run Code Online (Sandbox Code Playgroud)

,这会导致覆盖本机Promise元素.因为bluebird是规范的超集,所以它不会破坏现有代码,因此应该是安全的.

但是,因为我知道这被认为是不好的做法:

  1. 扩展或替换语言本地人,和
  2. 定义全局变量以在依赖于它的需求链中使用

当我想在节点应用程序的基本脚本中包含它时,我很谨慎:

import Promise from 'bluebird';
global.Promise = Promise;
Run Code Online (Sandbox Code Playgroud)

这是一种不好的做法吗?我应该坚持在每个文件中导入bluebird吗?

javascript overriding node.js promise bluebird

21
推荐指数
1
解决办法
5028
查看次数

如何在没有延迟的anit-pattern的情况下将jQuery $ .ajax调用转换为Bluebird promises

现在我在核心文件中使用promise.deferred.这允许我在中心位置解决承诺.我一直在读,我可能正在使用反模式,我想知道为什么它是坏的.

所以在我的core.js文件中我有这样的函数:

var getMyLocation = function(location) {    
    var promiseResolver = Promise.defer();

    $.get('some/rest/api/' + location)
        .then(function(reponse) {
            promiseResolver.resolve(response);
        )}
        .catch(function(error) {
            promiseResolver.reject(error);
        });

     return promiseResolver.promise;
}
Run Code Online (Sandbox Code Playgroud)

然后在我的getLocation.js文件中,我有以下内容:

var core = require('core');
var location = core.getMyLocation('Petersburg')
    .then(function(response) {
        // do something with data
    }).catch(throw error);
Run Code Online (Sandbox Code Playgroud)

在阅读了关于延迟反模式的Bluebird文档和许多博客文章后,我想知道这种模式是否实用.我可以将此更改为以下内容:

core.js

var getMyLocation = function(location) {
    var jqXHR = $.get('some/rest/api/' + location);
    return Promise.resolve(jqXHR)
        .catch(TimeoutError, CancellationError, function(e) {
            jqXHR.abort();
            // Don't swallow it
            throw e;
        });
Run Code Online (Sandbox Code Playgroud)

getLocation.js

var location = core.getMyLocation('Petersburg')
    .then(function(response) …
Run Code Online (Sandbox Code Playgroud)

javascript promise bluebird

20
推荐指数
1
解决办法
8702
查看次数

Promise被拒绝后停止运行进程

我正在使用以下代码工作正常,但问题是,当我收到错误时,我希望它停止所有其他的承诺.例如,如果chi.getCommand(val1, val2)将发送拒绝和我到了异常俘获,我想取消承诺的chss.exeapp.getStatus(12);我怎样才能做到这一点?

  var start = Promise.all([
      chi.getCommand(val1, val2),
      chi.findAndUpdateCustomer()
    ]).spread(function (command, customer) {
        return chss.exe(runnableDoc, command, customer)
                 .delay(10)
                 .then(function (val) {
                   if (val) console.log(val);
                   return app.getStatus(12);
                 });
    }).catch(function (err) {
        // catch and handle errors and when it come to here I want it to stops all the chain above
    });
Run Code Online (Sandbox Code Playgroud)

这是get命令的代码:

function getCommand(method, cmd) {
  return new Promise(function (resolve, reject) {
    ...
    child.stderr.on('data', function (data) {
        console.log('stderr: here!' + data);
        reject(data);
    });
} …
Run Code Online (Sandbox Code Playgroud)

javascript node.js promise bluebird

20
推荐指数
1
解决办法
6421
查看次数

与fs和蓝鸟的承诺

我目前正在学习如何在nodejs中使用promises

所以我的第一个挑战是列出目录中的文件,然后使用异步函数获取每个步骤的内容.我提出了以下解决方案,但有一种强烈的感觉,这不是最优雅的方式来做到这一点,尤其是我将异步方法"转变"为承诺的第一部分

// 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 …
Run Code Online (Sandbox Code Playgroud)

javascript asynchronous fs node.js bluebird

19
推荐指数
1
解决办法
1万
查看次数

EventEmitter位于Promises链中间

我正在做的事情涉及按顺序运行一系列child_process.spawn()(进行一些设置,然后运行调用者感兴趣的实际多肉命令,然后进行一些清理).

就像是:

doAllTheThings()
  .then(function(exitStatus){
    // all the things were done
    // and we've returned the exitStatus of
    // a command in the middle of a chain
  });
Run Code Online (Sandbox Code Playgroud)

在哪里doAllTheThings()是这样的:

function doAllTheThings() {
  runSetupCommand()
    .then(function(){
      return runInterestingCommand();
    })
    .then(function(exitStatus){
      return runTearDownCommand(exitStatus); // pass exitStatus along to return to caller
    });
}
Run Code Online (Sandbox Code Playgroud)

在内部我正在使用child_process.spawn(),它返回一个EventEmitter,我实际上将close事件的结果runInterestingCommand()返回给调用者.

现在我还需要将data来自stdout和stderr的事件发送给调用者,调用者也来自EventEmitters.有没有办法让(Bluebird)Promises使用它,或者它们只是阻碍了发出多个事件的EventEmitters?

理想情况下,我希望能够写:

doAllTheThings()
  .on('stdout', function(data){
    // process a chunk of received stdout data
  })
  .on('stderr', function(data){ …
Run Code Online (Sandbox Code Playgroud)

node.js promise bluebird

19
推荐指数
1
解决办法
6400
查看次数

bluebird.js vs bluebird.core.js有什么区别?

bluebird.js和bluebird.core.js有什么区别?

我什么时候应该使用bluebird.core.js而不是bluebird.js?

我无法在蓝鸟网站或其他地方找到任何东西.

bluebird

19
推荐指数
1
解决办法
1092
查看次数

由于异步生成器中的非并行等待承诺而导致速度下降

我正在使用生成器和Bluebird编写代码,我有以下内容:

var async = Promise.coroutine;
function Client(request){
    this.request = request;
}


Client.prototype.fetchCommentData = async(function* (user){
    var country = yield countryService.countryFor(user.ip);
    var data = yield api.getCommentDataFor(user.id);
    var notBanned = yield authServer.authenticate(user.id);
    if (!notBanned) throw new AuthenticationError(user.id);
    return {
        country: country,
        comments: data,
        notBanned: true
    };
});
Run Code Online (Sandbox Code Playgroud)

但是,这有点慢,我觉得我的应用程序等待I/O太多而且它不是并行的.如何提高应用程序的性能?

总响应时间为800 countryFor+ 400 getCommentDataFor+ + 600,authenticate因此总共1800ms这是很多.

javascript generator promise async-await bluebird

18
推荐指数
2
解决办法
3312
查看次数