![](/img/trans.png)
[英]promises.push() runs instantly and does not wait for promises.all()
[英]I'm pushing promises to an array inside a forEach using promises.push( promiseFunction( params ), but the promiseFunction is executed immediately
所以我想做的是將promise推送到forEach內的一個promise數組中,然后在forEach之后我要調用Promise.all(promise數組),但是每個promise立即執行,因此Promise.all從不到達。
下面是代碼:
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的理解不佳,您必須以某種方式學習,是嗎?
根據@bergi( https://meta.stackexchange.com/users/183280/bergi ),這是預期的功能。
為了在返回承諾之前進行驗證,我剛剛使用了一個forEach進行驗證,並使用了另一個@Epi來將其添加到promises數組中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.