J'essaie d'obtenir une liste d'entités correspondantes à partir d'une chaîne de requête. J'utilise s3 pour stocker mes objets.Problème avec la promesse async
Le problème est que la promesse qui résout la «promesse principale» est ansych ne retourne le tableau que lorsque setTimeOut
. Sinon, il renvoie [undefined, undefined...]
.
mon code ressemble à ceci:
getEntities: (type, offset, limit, query) => {
return new Promise((resolve, reject) => {
seekKeys(type, offset, limit, query)
.then((response) => {
let entities = [];
if (response.hasBeenFiltered) { // This is not used yet.
for (let i = offset; i < response.keys.length && i < offset + limit; i++) {
entities.push(matchInstance(instance))
}
resolve(entities)
} else { // here is where my issue's at.
console.log("Keys found: " + response.keys.length)
parseQuery(type, query)
.then((conditions) => {
let matches = response.keys.map((key) => {
readEntity(key).then((instance) => {
logger.debug(instance); // logs instances.
matchInstance(instance, conditions)
.then((isMatch) => {
logger.debug("isMatch", isMatch) // logs true/false ?
if (isMatch) {
entities.push(instance);
}
})
.catch((err) => {
logger.error("Failed to match entity: ", err)
})
})
.catch((err) => {
logger.error("Failed to read entity: ", err)
})
});
/*
Promise.resolve(matches)
.then(() => {
setTimeout(() => {
logger.debug("Match count:", entities.length);
logger.debug("Matching entities:", entities) // logs result of entities
}, 5000)
//resolve(entities)
})
*/
Promise.resolve(matches)
.then(() => {
logger.debug("Match count:", entities.length);
logger.debug("Matching entities:", entities) // logs [undefined, undefined ....]
resolve(entities)
})
})
.catch((err) => {
console.error("Failed to parse query: ", err)
});
})
})
}`
Le format est un peu cassé. Je suis tout à fait sûr pourquoi. S'il vous plaît laissez-moi savoir si vous avez besoin de plus d'informations.
Copie possible de [Comment renvoyer la réponse d'un appel asynchrone?] (Https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous- call) – Liam
Évitez le ['anti-modèle de constructeur' 'Promise'] (https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it)! – Bergi