javascript - Pass outer variable into promise .then without calling it -


i have series of promise functions i'm chaining together. don't need specific result previous function i'm not adding resolve(); need them run sequentially.

however, there variable in containing scope want pass first , fourth(last) promise. when add parameter third promise, function runs immediately.

how can pass parameter chained promise , not call function/promise @ time?

here basics of i'm trying do:

const containingfunction = function() {         const vartopass = document.queryselector("#id").value.trim();         firstpromise(vartopass)             .then(secondpromise)             .then(thirdpromise)             .then(fourthpromise(vartopass))             .catch(e =>{                console.error(e));              } );     }; 

fourthpromise:

    const fourthpromise = function(varpassed) {             return new promise(function(resolve, reject) {                 stuff after thirdpromise has been resolved                 console.log(varpassed)                 resolve();             });         }; 

you have 2 possibilities depending on how want resolve vartopass.

lambda

using lambda function (anonymous function without own scope) described @jaromanda x:

() => return fourthpromise(vartopass) 

which cause function keep reference variable , not value. value of vartopass evaluated fourthpromise fired, not when code run.

wrapper

the second option using wrapper, i.e. function returns function:

function fourthpromise(vartopass) {     return function() {         return new promise(function(resolve, reject) {             stuff after thirdpromise has been resolved             console.log(vartopass)             resolve();         });     }; } 

in case value of passed variable evaluated @ time code runs , not when callback called.

which option better applicable case can't tell without more context though.


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -