javascript - 向 promise 链添加附加方法

标签 javascript node.js promise bluebird

我使用以下代码,工作正常,当前 pars.getEx 返回一个字符串以运行到 processExe 方法,现在我还需要以某种方式传递 port从其他函数到processExe,我该怎么做?

  var portscanner = require('portscanner');
  var Promise = require('bluebird');
  var fs = Promise.promisifyAll(require("fs"));

......

    return fs.readFileAsync(filePath, 'utf8')
        .then(pars.getEx.bind(null, 'user'))
        .then(processExe.bind(null, 'exec'))
        .then(function (result) {
            return result.stdout;
        }, function (error) {
            return error;
        });

processExe 如下所示

function processExe(method, cmd) {
    return new Promise(function (resolve, reject) {

        var child = child_process[method](cmd, function (error, stdout, stderr) {

可以通过以下操作系统实现该移植

https://github.com/baalexander/node-portscanner

portscanner.findAPortNotInUse(3000, 4000, 'localhost', function (error, 

port) {

更新

对于 processExe,我应该提供如下端口

端口应该来自findPort

       var options = {
            PORT: port,
        };

这里我还传递了选项

var child = child_process[method](cmd,options, function (error, stdout,

最佳答案

如果您想要/需要参数,只需添加一个参数:

function processExe(method, cmd, port) {
    return new Promise(function (resolve, reject) {
        var child = child_process[method](cmd, {
            PORT: port,
        }, function (error, stdout, stderr) {
            …
        });
        …
    });
}

与往常一样,异步函数应该返回一个 Promise,它有多少个参数(一个、两个或现在三个)并不重要。您不应该尝试找到某种特殊的方法来传递所需的值,因为该函数将在某些情况下使用,这是一个单独的问题,不应影响函数的设计。

现在,当在 Promise 链中调用函数时如何传递附加参数?好吧,您似乎已经知道函数表达式和 .bind 可以为您服务了。问题在于,参数值的来源不是单个 promise ,而是两个异步进程 - 一个读取和解析文件,另一个查找端口。由于两者都是异步的,我们期望它们都返回 Promise;您应该能够像 fs 那样 promisify portscanner

当您有两个或多个 Promise 时,可以使用 Promise.all 将它们组合起来:

return Promise.all([
    fs.readFileAsync(filePath, 'utf8').then(pars.getEx.bind(null, 'user')), 
    portscanner.findAPortNotInUseAsync(3000, 4000, 'localhost')
]).then(function(args) {
    return processExe('exec', args[0], args[1]);
})

我们可以通过使用Promise.join来稍微简化一下:

return Promise.join(
  fs.readFileAsync(filePath, 'utf8').then(pars.getEx.bind(null, 'user')), 
  portscanner.findAPortNotInUseAsync(3000, 4000, 'localhost'),
  processExe.bind(null, 'exec')
)

关于javascript - 向 promise 链添加附加方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31921693/

相关文章:

javascript - 构造函数中的异步操作

AngularJS - 绑定(bind)/监视返回 promise 的函数

javascript - 箱线图中的 Highcharts : Display the labels (min, 最大值、中值等)

javascript - 如何获取一个键用作 lodash map 函数中的变量?

mysql - 在node,js中等待MySQL查询执行

javascript - NuxtJS : EmailJS Can't Find Dependency 'fs'

sql - 使用 Node.js 连接表的 GraphQL 查询

javascript - 使用 Chrome 扩展程序在页面加载时重定向

javascript - 使用一个 jQuery AJAX 表单(或响应)返回两个数据库结果

javascript - 将 Javascript Promise 放入函数中