我需要向promise传递一些参数,但是promise只接受两个参数(resolve和reject)。我已经看到过类似的关于将参数传递给.then()函数的问题,但是没有关于诺言本身的问题。有办法使它起作用吗?如果没有,任何解决的建议将不胜感激。谢谢
答案 0 :(得分:3)
从广义上讲,可以遵循这些原则(使用闭包)。让我知道它是否可以解决您的用例。否则,让我知道。
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)
答案 1 :(得分:0)
您用来解决承诺的任何内容都将用作该承诺之后的.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;
});