作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
所以我想做的是将 promise 推送到 forEach 中的一系列 promise ,然后在 forEach 之后我想调用 Promise.all( promise 数组),但是每个 promise 都会立即执行,因此 Promise。一切都未达到。
代码如下:
function updatePersonsPreferences( personId, preferences ) {
return new Promise( ( resolve, reject ) => {
const promises = [];
const methods = preferences.methods;
let validationError = null;
methods.forEach( ( method ) => {
// I do some validation here using a validation helper which is in another file
const functionSchema = {
person_id: { type: "integer", required: true },
type: { type: "integer", required: true },
frequency: { type: "integer", required: true },
};
const data = {
person_id: personId,
type,
frequency,
};
const validationResult = validator.isValidFunctionParameters( functionSchema, data );
if ( !validationResult.valid )
validationError = validationResult.error;
promises.push( updateMethod( personId, method.id, method.status ) ); // This is getting executed immediately when it shouldn't be
} );
// This does reject, but the promises are still run
if ( validationError ) {
return reject( validationError );
}
// EDIT: Moved console log below the rejection code above, and it is now logging [ Promise { <pending> }, Promise { <pending> } ]
console.log( promises );
// The code below never seems to be reached
return Promise.all( promises ).then( ( results ) => {
return resolve();
}, reject );
} );
}
function updateMethod( personId, methodId, status ) {
return new Promise( ( resolve, reject ) => {
// Does some database logic here
return Method.update( {
// Database logic here
} ).then( ( result ) =>
return resolve( result );
}, ( error) => {
return reject( error );
} )
} );
}
最佳答案
// The code below never seems to be reached
*return* Promise.all( promises ).then( ( results ) => {
return resolve();
}, reject );
乍一看还不错,但请尝试进行上述更改,如果有效请告诉我。
编辑:
return Promise.all(methods.map(method => {
return updateMethod( personId, method.id, method.status );
})).then(function(results) {
return resolve(results);
});
关于javascript - 我正在使用 promises.push( promiseFunction( params ) 将 promises 推送到 forEach 中的数组,但 promiseFunction 会立即执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44658582/
所以我想做的是将 promise 推送到 forEach 中的一系列 promise ,然后在 forEach 之后我想调用 Promise.all( promise 数组),但是每个 promise
我是一名优秀的程序员,十分优秀!