Reputation: 1
I am getting a little delay on array update. My front-end (React.js) gets access before the back-end (node.js) updates it. Here is my back-end code:
router.get("/images/files", (req, res, next) => {
let links = [];
fileSchema
.find()
.then(doc => {
doc.map(data => {
client.files.getEmbedLink(data.fileID).then(file => {
links.push(file);
return res.status(200).json({
status: "success",
message: "Links are ready!",
links: links
});
});
});
});
As you can seeIi am pushing links inside another array but I don't know how to respond when the array is fully updated.
Upvotes: 0
Views: 143
Reputation: 12089
You will need to wait for all of the promises from your getEmbedLink
calls to resolve before sending your response.
This should help:
router.get("/images/files", (req, res, next) => {
fileSchema
.find()
.then(doc => {
// Create an array of promises
const promises = doc.map(data => {
return client.files.getEmbedLink(data.fileID)
});
// Wait for all promises to resolve
return Promise.all(promises)
})
.then(links => {
// "links" will be an array of results
res.status(200).json({
status: "success",
message: "Links are ready!",
links: links
});
})
.catch(err => {
// Handle error
});
});
Upvotes: 1