tom894
tom894

Reputation: 519

Passing Arguements to Promises

I need to pass some arguments to a promise but promises only take two parameters (resolve and reject). I've seen similar questions about passing arguments into .then() functions, but none about the promises themselves. Is there a way to make it work? If not, any suggestions for work around would be greatly appreciated. Thanks

Upvotes: 0

Views: 45

Answers (2)

Shilly
Shilly

Reputation: 8589

Anything you use to resolve the promise with, will be used as the parameters for the .then() call following that promise:

// A function containing a promise.
const get_data = () => {
  return new Promise(( resolve, reject ) => {
    // some logic determining if the promise has to resolve or reject.
    const valid = true;
    // Pass all different parameters as a object we can destructure.
    if ( valid ) resolve({ num: 1, str: 'some string', ary: [ 'data' ] });
    else reject( new Error( 'something went wrong' ));
  });
};

// Call the function that returns the promise.
get_data()
  // destructure the object back into individual variables.
  .then(({ num, str, ary }) => {
    // Do things with the parameters.
    console.log( `the number parameter is: ${ num }` );
    console.log( `the string parameter is: ${ str }` );
    console.log( `the array  parameter is: ${ ary }` );
  })
  // Catch any erros in the promise chain.
  .catch( error => {
    console.error( 'The promise rejected' );
    throw error;
  });

Upvotes: 0

trk
trk

Reputation: 2228

Broadly it can be along these lines (using closure). Let me know if it solves your use case. Else, let me know.

function asyncFunction(arg1, arg2 ... ) {
    return new Promise(function(resolve, reject){
        //use arg1, arg2 and so on. And, after your async call 
        if(arg1 === true) {
           setTimeout(resolve,200) //e.g. async function
       } else {
            reject(arg2)
       }
    })
}

And, finally don't forget to call:

asyncFunction(true, 2)

Upvotes: 3

Related Questions