简体   繁体   English

将承诺传递给承诺

[英]Passing Arguements to Promises

I need to pass some arguments to a promise but promises only take two parameters (resolve and reject). 我需要将一些参数传递给Promise,但是Promise仅采用两个参数(解析和拒绝)。 I've seen similar questions about passing arguments into .then() functions, but none about the promises themselves. 我已经看到过类似的关于将参数传递给.then()函数的问题,但是没有关于诺言本身的问题。 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: 用于解决承诺的任何内容都将用作该承诺后的.then()调用的参数:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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