Promise join为链添加新函数调用

sho*_*a T 6 javascript node.js promise bluebird

我正在尝试加载和解析文件,但是在调用两个函数并返回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]);
....
Run Code Online (Sandbox Code Playgroud)

我已将该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]);
....
Run Code Online (Sandbox Code Playgroud)

但它不起作用.我在这做错了什么?

UPDATE

var ymlParser = require('yamljs');
var ymlObj;

parse = function ( data) {
    "use strict";
    if (!ymlObj) {
        ymlObj = ymlParser.parse(data);
    }
    return ymlObj;
};

getProcWeb = function () {
    return ymlObj.prop.web;
};

module.exports = {
    parse: parse,
    getProp: getProp
};
Run Code Online (Sandbox Code Playgroud)

Chu*_*uan 1

在您的情况下,Promise.join 不会返回数组 - args[]。Promise.all 将返回一个数组。

因此,在您的情况下,您应该将 Promise.join 语法更改为

    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))
       ,function(argsOne,argsTwo){
           return runProc('run', argsOne, argsTwo);
   }));
Run Code Online (Sandbox Code Playgroud)

或者使用 Promise.all

   Promise.all([promise1, promise2]).then(function(args){
       return runProc('run', args[0], args[1]); 
   });
Run Code Online (Sandbox Code Playgroud)