简体   繁体   中英

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

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)

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; }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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