我试图加载和解析一个文件,但我有一些麻烦调用两个函数并返回结果的承诺。我用的是蓝鸟的承诺。下面的代码按预期工作:
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]);
....
我将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]);
....
但是它不工作。我哪里做错了?
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
};
承诺。Join不会返回一个数组,在你的例子中是args[]。的承诺。都将返回一个数组
所以在你的情况下,你应该改变你的承诺。
的连接语法 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);
}));
或者使用Promise.all
Promise.all([promise1, promise2]).then(function(args){
return runProc('run', args[0], args[1]);
});