简体   繁体   English

Promise join为链添加新函数调用

[英]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. 我正在尝试加载和解析文件,但是在调用两个函数并返回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.parse函数划分为两个方法, parseFile.parseparseFile.getProp parseFile.getProp should take the output from parseFile.parse and return what parseFile.parse returned before the method was split up. parseFile.getProp应该从parseFile.parse获取输出并返回在拆分方法之前返回的parseFile.parse 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 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
};

Promise.join won't return an array, in your case - args[]. Promise.join不会返回一个数组,在你的情况下 - args []。 Promise.all will return an array. Promise.all将返回一个数组。

So in your case, you should either change your Promise.join syntax to 因此,在您的情况下,您应该将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);
   }));

Or use Promise.all 或者使用Promise.all

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM