gpt4 book ai didi

javascript - 我正在使用 promises.push( promiseFunction( params ) 将 promises 推送到 forEach 中的数组,但 promiseFunction 会立即执行

转载 作者:搜寻专家 更新时间:2023-11-01 00:38:03 24 4
gpt4 key购买 nike

所以我想做的是将 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com