Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Promise join add new function call to the chain

I am trying to load and parse a file, but am having some trouble calling two functions and returning the result for the promise. I am using bluebird promises. The following code works as expected:

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]);
....

I have divided the parseFile.parse function into two methods, parseFile.parse and parseFile.getProp. parseFile.getProp should take the output from parseFile.parse and return what parseFile.parse returned before the method was split up. Here is my attempt to use both functions:

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]);
....

but it isn't working. What am I doing wrong here?

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
};
like image 847
07_05_GuyT Avatar asked Aug 23 '15 13:08

07_05_GuyT


1 Answers

Promise.join won't return an array, in your case - args[]. Promise.all will return an array.

So in your case, you should either change your Promise.join syntax to

    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);
   }));

Or use Promise.all

   Promise.all([promise1, promise2]).then(function(args){
       return runProc('run', args[0], args[1]); 
   });
like image 182
Chuan Avatar answered Oct 04 '22 22:10

Chuan