繁体   English   中英

将承诺传递给承诺

[英]Passing Arguements to Promises

我需要将一些参数传递给Promise,但是Promise仅采用两个参数(解析和拒绝)。 我已经看到过类似的关于将参数传递给.then()函数的问题,但是没有关于诺言本身的问题。 有办法使它起作用吗? 如果没有,任何解决的建议将不胜感激。 谢谢

大致上可以遵循这些原则(使用闭包)。 让我知道它是否可以解决您的用例。 否则,让我知道。

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

最后,不要忘了打电话:

asyncFunction(true, 2)

用于解决承诺的任何内容都将用作该承诺后的.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