const maxParallelRequests = 1;
const limit = pLimit(maxParallelRequests);
// Use the map method to create an array of promises for each call to GetData
const promises = items.map(item => {
limit(() => this.getData(item))
});
When I log promises I get an array of 60 undefined items.
What am I doing wrong here?
item is defined inside the map function.
I had to add return in the map:
// Use the map method to create an array of promises for each call to GetData
const promises = items.map(item => {
return limit(() => this.getData(item))
});
Related
The function loops through an array from the request body and checks if the productId property is valid if it's valid I push to a new array existingProductId, but it ends up returning an empty array. Please any ideas or solution.
function returnValidId(products){
var existingProductId = [];
products.map(async(product)=>{
const existingProduct = await Product.findById(product.productId)
if(existingProduct){
existingProductId.push({id:existingProduct._id})
}
})
return existingProductId;
}
const data = returnValidId(products)
console.log(data)
You are using .map and you are returning promises, but you are not waiting the resolve of those promises and the function returns the empty array. Try:
async function returnValidId(products){
var existingProductId = [];
await Promise.all(products.map(async(product)=>{
const existingProduct = await Product.findById(product.productId)
if(existingProduct){
existingProductId.push({id:existingProduct._id})
}
}));
return existingProductId;
}
const data = await returnValidId(products)
console.log(data)
With Promise.all you are waiting for the promises to be resolved.
I have a Cloud function which I am trying to get to increment a field in Firestore:
exports.incrementUpvotes = functions.https.onCall((data, context) => {
async function incrementValue() {
const Id = data.thisId;
const increment = firebase.firestore.FieldValue.increment(1);
const docRef = admin.firestore().collection('posts').doc(Id)
docRef.update({ upvoteCount: increment })
};
return incrementValue()
})
I have tried lots of variations of the above. Each time it fails with this error: Uncaught (in promise) Error: INTERNAL
I'm calling it just using this:
const incrementUpvotes = getFunctions.httpsCallable('incrementUpvotes')
EDIT: getFunctions is an export from my Firebase.js ie. firebase.functions()
and then this in a function:
incrementUpvotes({thisId})
Can anyone see what I'm doing wrong?
You're neither returning anything nor using await in your incrementValue function, which means that it ends up returning undefined.
Since docRef.update is an asynchronous call, you'll want to either await that or return the promise it returns.
So:
function incrementValue() { // 👈 Removed async
const Id = data.thisId;
const increment = admin.firestore.FieldValue.increment(1); // 👈 Use admin
const docRef = admin.firestore().collection('posts').doc(Id)
return docRef.update({ upvoteCount: increment }) // 👈 Added return
};
I have a function which contains a thousand of objects in an array:
function Alltransaction(transactionArray) {
transactionArray.map(async (transaction) => {
dataAgainsthash = await web3.eth.getTransaction(transaction)
TransactionObject = {
transactionHash : transaction,
from : dataAgainsthash.from
};
transactionArray.push(TransactionObject)
console.log("transaction array", transactionArray)
});
}
then i have another function which stores these thousands of object array into db
function saveTransactionToDb() {
console.log("after loop",transactionArray)
transactionss = new Transaction({
blockNumber : blockNumbers ,
transactions : transactionArray
})
// Now save the transaction to database
await transactionss.save();
// console.log("save to database")
}
then I call this in my router
await Alltransaction(transactionArray);
await saveTransactionToDb();
and I also try
Alltransaction(transactionArray).then(saveTransactionToDb())
But it always runs saveTransactionToDb() before the array of object populates the Alltransaction() method
have you try the async keyword before saveTransactionToDb and Alltransaction functions??
async function Alltransaction(transactionArray){
// your code
}
async function saveTransactionToDb(){
// your code logic*
await transactionss.save();
}
First, in Alltransaction the promise must be returned as well. In your code the function starts some processes but doesn't not await on it. Also, do not push the promises to the original array. I'm not sure what you were trying to accomplish there. Because mapping over the array gives you an array of promises, you can unify all of them with Promise.all().
function Alltransaction(transactionArray) {
const promises = transactionArray.map(async (transaction) => {
dataAgainsthash = await web3.eth.getTransaction(transaction)
const TransactionObject = {
transactionHash : transaction,
from : dataAgainsthash.from
};
return TransactionObject;
});
return Promise.all(promises);
}
Change saveTransactionToDb to receive an array instead of using the original array.
Then you'll be able to call it as:
const t = await Alltransaction(transactionArray);
await saveTransactionToDb(t);
Your second try it's not correct:
Alltransaction(transactionArray).then(saveTransactionToDb())
It's the same as:
const t = Alltransaction(transactionArray);
const s = saveTransactionToDb();
t.then(s)
That's why saveTransactionToDb doesn't way for transactions to complete. To use then, just pass the function without calling it:
Alltransaction(transactionArray).then(saveTransactionToDb)
Hello I have the following code, I want to use async.parallel and Q.all function for parallel execution of functions calling.
Should I use or not Please reply, All your answers are appreciations.
function getPath(x){
return (x/100); // It's demo here it's some big logic exist.
}
var array = [4,56,2,3,34,45,65,23,23,12,12,23,34,43,54,54]; // lack of data in array
var resultArr = [];
array.forEach(function(val){
resultArr.push(getPath(val));
})
// After 5-8 sec, I got results.
Can I execute the same things using async.parellel or Q.all How?
Q and promises are able to mix, and you can even await Q promises that are A+ compatible. Here is an example using promises and another with async/await
function readDir(x) {
return new Promise(function(rs){
setTimeout(rs, x, x)
})
}
function getPath(x) {
return readDir(x).then(function(val){
return val / 100
})
}
var array = [4,56,2,3,34,45,65,23,23,12,12,23,34,43,54,54]; // lack of data in array
var resultArr = array.map(function(val) {
return getPath(val);
});
// Q.all is the equivulant of Promise.all
Promise.all(resultArr).then(console.log)
function readDir(x) {
return new Promise(function(rs){
setTimeout(rs, x, x)
})
}
async function getPath(x) {
var val = await readDir(x)
return val / 100;
}
async function init() {
var array = [4,56,2,3,34,45,65,23,23,12,12,23,34,43,54,54]; // lack of data in array
var resultArr = array.map(function(val) {
return getPath(val);
});
var result = await Promise.all(resultArr);
console.log(result)
}
init()
node v10 ships with fs.promises that are pretty neat.
async function getPath(x) {
const files = await fs.promises.readdir(x)
console.log(files)
}
all functions that are async returns a promise
In this err.length code always returns []. Where am I going wrong?
err.length does not wait for map result
router.post('/add', authSigs, async (req, res) => {
const nds = req.body.nds
const split = nds.split('\n')
const err = []
await split.map(async item => {
let sub = item.substr(0, 7)
const checkModel = await modelSerial.findOne({
'modelNds': sub
})
if (!checkModel) err.push(item)
})
if (err.length > 0) return res.status(400).send({error: 'Invalid'})
return res.status(200).send()
})
You're not awaiting on a Promise, you're doing await [Promise, Promise] so, your await isn't actually waiting for all the promises to resolve, you need to use Promise.all, which takes an array of promises.
The Promise.all(iterable) method returns a single Promise that
resolves when all of the promises in the iterable argument have
resolved or when the iterable argument contains no promises. It
rejects with the reason of the first promise that rejects.
const promises = split.map(async item => {
let sub = item.substr(0, 7)
const checkModel = await modelSerial.findOne({
'modelNds': sub
})
if (!checkModel) err.push(item)
});
await Promise.all(promises);
// Now all promises have been resolved
// err will contain items if there were any errors