javascript - I still get the pyramid of doom when using promises, what am I doing wrong? -
i using inquirer library node.js , still pyramid of doom when using promises, doing wrong?
just fyi inquirer library api basically:
inquirer.prompt([ question1, question2, question3, ... questionx ]).then(function(answers){});
where answers hash, keys represent each question. nothing out of ordinary here.
anyway, using api, getanswerstoprompts().then(function(answers){})
, seems more convenient keep nesting promises inside previous one...like so:
function run (rootdir) { return watchhelper().then(function (answers) { return choosedirs({ allowdirs: answers.allow, originalrootdir: rootdir, onlyonefile: false }).then(function (pathstorun) { assert(pathstorun.length > 0, ' need select @ least 1 path.'); return getoptions(availableoptionsforplainnode).then(function (answers) { const selectedopts = answers[ 'command-line-options' ]; return localorglobal().then(function (answers) { const sumanexec = answers.localorglobal; console.log(' => ', colors.magenta.bold([ '$', sumanexec, '--watch', pathstorun, selectedopts ].join(' '))); }); }); }); }).catch(rejectionhandler); }
i possibly instead:
function run(){ return makepromise() .then(fn1(data1)) .then(fn2(data2)) .then(fn3(data3)) }
where fn1,fn2,fn3 like:
function fnx(data){ return function(answers){ return promise(data); } }
but makes things more complicated understand afaict
just clear possible, need result of previous promise, need result promise prior or result prior that.
nesting functions allows data need in scope, closures etc.
return next promise before calling then
:
function run (rootdir) { var pathstorun; return watchhelper() .then(function (watchhelperanswers) { return choosedirs({ allowdirs: watchhelperanswers.allow, originalrootdir: rootdir, onlyonefile: false }); }).then(function (choosedirsresult) { assert(choosedirsresult.length > 0, ' need select @ least 1 path.'); pathstorun = choosedirsresult; return getoptions(availableoptionsforplainnode); }).then(function (getoptionsanswers) { const selectedopts = getoptionsanswers[ 'command-line-options' ]; return localorglobal(); }).then(function (localorglobalanswers) { const sumanexec = localorglobalanswers.localorglobal; console.log(' => ', colors.magenta.bold([ '$', sumanexec, '--watch', pathstorun, selectedopts ].join(' '))); }).catch(rejectionhandler); }
but need result promise prior or result prior that
the instance of in example pathstorun
. think nesting functions 2 or 3 deep accommodate still readable, other option define variable outside promise chain, have shown above pathstorun
.
lastly, example uses 3 different variables called answers
throughout promise chain, might adding confusion. in general think fine use same name promise callback results, have renamed them here clarity in answer.
Comments
Post a Comment