Promise Pending while using map function [duplicate] - javascript

This question already has an answer here:
How to get a value from a "Promise" object
(1 answer)
Closed 4 years ago.
I'm trying to use the mongoose to try to fetch all the records under the Profile Schema using the find() method. The code looks fine to me and when I console.log the code block, it returns Promise { <pending> }.
I tried different approaches with no hope. Any help would be appreciated.
Thanks,
Here is my Code:
return Profile.find()
.then(profiles => {
return profiles.map(profile =>{
return {
...profile._doc
};
});
}).catch(err => {
//console.log(err);
throw err;
})

That would be because the promise is in pending state.If you need the data after the promise has been resolved you would have to add a then callback.
function getProfiles(){
return Profile.find()
.then(profiles => {
return profiles.map(profile =>{
return {
...profile._doc
};
});
}).catch(err => {
//console.log(err);
throw err;
})
}
getProfiles().then(profiles => console.log('profiles',profiles))

Related

Variable is not storing Promise result in Node [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
How do I access previous promise results in a .then() chain?
(17 answers)
Closed 2 years ago.
I'm developing a script that connects with an API, then with the JSON reponse do some operations and then reformat the JSON to send it to another API.
But now I'm stuck in the first step as I can't deal with the first part as my Promises is not working as expected. How can I store the API's response into a variable? For development puropose I stored one API response into a JSON file. This is my code:
declare var require: any;
let url = './data/big buy/big-bui-product-list.json';
const fs = require('fs');
let counter = 0;
const getProductList = () => {
return new Promise((resolve, reject) => {
fs.readFile(url, 'utf8', (err, data) => {
if(err){
return reject (err);
}
else {
return resolve(JSON.parse(data));
}
})
})
}
const getProductStock = () => {
return new Promise((resolve, reject) => {
fs.readFile('./data/big buy/big-bui-product-stock.json', 'utf8', (err, data) => {
if(err) {
return reject(err);
}
else {
return resolve(JSON.parse(data));
}
})
})
}
try {
let products;
console.log('Products:');
Promise.all([getProductList()])
.then(function(result) {
products = result[0];
});
console.log('Stocks:');
const productStock = Promise.all([getProductStock()]);
console.log(products);
}
catch(e) {
console.log((`Ha ocurrido un error: ${e.message}`));
}
finally {
}
In this code, what I do is getting a list of products and then get the stocks of all the products, later I will add a new function that will filter by stock and get me just a list of products where stock is bigger than X units. Now when I launch it from the terminal I dont' get the response stored into products variable but if I add .then((data) => console.log(data)) into the Promise I see on screen the JSON but as I dont' have it stored it in any variable I don't see how can I work with the objects I'm retrieving.
Promises are asynchronous. They are quite literally promises that a value will be yielded in the future. When you do getProductList().then(x => products = x), you're saying that Javascript should fetch the product list in the background, and once it's finished, it should set the products variable to x. The key words there are "in the background", since the code afterwards keeps running while the product list is being fetched. The products variable is only guaranteed to be set after the .then portion is run. So, you can move things into the .then:
try {
let products;
getProductList().then(list => {
products = list;
return getProductStock(); // leverage promise chaining
}).then(stocks => {
console.log("Products:", products);
console.log("Stocks:", stocks);
});
}
catch(e) {
console.log((`Ha ocurrido un error: ${e.message}`));
}
finally {
}
You seem to be missing some fundamental knowledge about promises. I suggest reading through the MDN Using Promises guide to familiarize yourself a bit with them.
A structure like below never works.
let variable;
promise.then(data => variable = data);
console.log(variable);
This is because it is executed in the following manner.
Create the variable variable.
Add a promise handler to the promise.
Log variable.
Promise gets resolved.
Execute the promise handler.
Set variable variable to data.
If you are using Node.js 10 or higher you can use the promise API of file system to simplify your code quite a bit.
const fs = require('fs/promises');
const readJSON = (path) => fs.readFile(path, "utf8").then((json) => JSON.parse(json));
const getProductList = () => readJSON("./data/big buy/big-bui-product-list.json");
const getProductStock = () => readJSON("./data/big buy/big-bui-product-stock.json");
Promise.all([
getProductList(),
getProductStock(),
]).then(([products, stocks]) => {
console.log({ products, stocks });
}).catch((error) => {
console.log("Ha ocurrido un error:", error.message);
}).finally(() => {
// ...
});

Resolving a promise within a function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
I am having trouble resolving this promise.
const getAge = (actorId) => {
return (
axios.get(`https://api.themoviedb.org/3/person/${actorId}?api_key=${process.env.REACT_APP_API_KEY}&language=en-US`)
.then(function (response) {
return moment().diff(response.data.birthday, 'years')
})
.catch(function (error) {
console.log(error);
})
)
}
console.log(getAge('5000'), 'FUNCTION')
It doesnt ever resolve the promise and returns pending
I have tried a number of different ideas and none seem to work. What Am I missing?
Thanks
You need to call .then to get the value or wrap the call within a async function. For example:
getAge('5000')
.then(val => console.log(val, 'FUNCTION'));
Alternatively, wrapping with async:
(async () => {
const val = await getAge('5000');
console.log(val, 'FUNCTION');
})();

I can't return an object value, but it is showed up by console.log [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I'm trying to return a string value of an object generated by aws translate, the structure's object is
{
TranslatedText: "Hola",
SourceLanguageCode: "en",
TargetLanguageCode: "es"
}
the function
this.translate.translator.translateText(params, (err, data) => {
if (err) {
console.log(err, err.stack)
return err.stack;
}
if(data) {
console.log("translation :");
console.log(data.TranslatedText);
return data.TranslatedText;
}
});
I can see the string in console, but it is not returning it.
I think that I'm misunderstanding some async job here, and maybe the returned value is actually getting an undefined, but I'm not clear.
As it is in a callback function, so you won't be able to return the data like the way you are doing. Try using promises instead.
If doesn't make sense to return values from callbacks. Do what you want to do with the return value inside your callback.
Sounds like translateText is an async function. Therefore, await it like so:
this.translate.translator.translateText(params, (err, data) => {
if (err) {
console.log(err, err.stack)
return err.stack;
}
if(data) {
console.log("translation :");
console.log(data.TranslatedText);
return data.TranslatedText;
}
});

How to wrap a conditional statement in a Promise [duplicate]

This question already has answers here:
if-else flow in promise (bluebird)
(3 answers)
Closed 4 years ago.
I have a conditional if statement who's logic needs to be wrapped in a promise as the logic after if can only be executed after it.
// WRAP 'if' statement below IN A PROMISE
if (a) { // could be true or false. If false, resolve the promise
// logic here
}
.then(
// execute logic after if here
)
I'm new to nodejs and am trying to wrap my head around this. How can I solve this ?
Just wrap it into a new Promise:
new Promise((resolve, reject) => {
if(a){
reject("error");
} else {
resolve(yourData);
}
})
.then(data => {
// Do stuff
})
.catch(err => {
// You should catch here an error rejected above
})
The question is unclear a bit. Here is answer according to what I understand. You can not run code inside promise once it is resolved or rejected.
new Promise((res, rej) => {
if (false) {
}
res();
console.log('More code') // this will not run
}).then(() => {
console.log('This will run')
})

JavaScript - async/await not waiting for promise to resolve [duplicate]

This question already has answers here:
Using async/await with a forEach loop
(33 answers)
Closed 5 years ago.
I want to use Mongoose's bulk operation for upserting transactions. For each of my transactions I want to process them in a loop and within that loop I need to use a promise. After that promise resolved, I want to add the upsert to the bulk.
My problem here is, that although I await for every promise to finish, the bulk is executed at the end of the function before any of the promises is resolved. What am I doing wrong or how can I fix this?
const bulkTransactions = Transaction.collection.initializeUnorderedBulkOp();
transactions.forEach( async (transaction: any) => {
// do some suff, fill transaction_data
await Utils.processTransactionType(transaction).then((action: any) => {
if (action) {
// do other stuff
}
bulkTransactions.find({_id: hash}).upsert().replaceOne(transaction_data);
}).catch((err: Error) => {
// log error
});
});
await bulkTransactions.execute().catch((err: Error) => {
// log error
});
As far as I know, when using await, you no longer use the then return value:
const bulkTransactions = Transaction.collection.initializeUnorderedBulkOp();
transactions.forEach( async (transaction: any) => {
// do some suff, fill transaction_data
let action = await Utils.processTransactionType(transaction);
if (action) {
// do other stuff
}
bulkTransactions.find({_id: hash}).upsert().replaceOne(transaction_data);
});
await bulkTransactions.execute().catch((err: Error) => {
// log error
});

Categories