Async Await Promise <Pending> - node.js

I know this question been asked for many times but as I'm still very new i dont quite understand the answers on previous places.
const publicIp = require('public-ip');
// getting ip address
async function GetIpAddress() {
var a = await publicIp.v4();
return await a;
// it will return my public ip as string
}
however ,as its non blocking i understand if i do something like this as below
var a = GetIpAddress();
console.log(a);
it will probably go promise pending. so what i did was
async function hi(){
var a = await GetIpAddress();
console.log(a);
}
hi();
But here's my question. How do i return it back to my variables without making another function to cover it up? please see code below
var zmq = require('zmq'),
requester = zmq.socket('req'),
publicIp = require('public-ip');
const PORT = "3222";
var IP = GetIpAddress();
console.log(`${IP}:${PORT}`);
// IP will return promise pending?? how i do fix this without making another
// function?
requester.connect('tcp://127.0.0.1:5433');
requester.on('message', function (msg) {
// arr = str.split(",");
console.log(msg.toString());
});
requester.send(
`${IP}:${PORT}`
);
async function GetIpAddress() {
var a = await publicIp.v4();
return a
}
As the full code above shown.. var IP will definitely be promise pending as it will take time. therefore how do it get the function return value without making another function?
EDIT: please understand the duplication is entirely not what i want.. I understand that my knowlege on callbacks , promises and async await wasnt strong but from a guy who comes from synchronous language such as Python itself . I'm very curious onto how do i take variable out. as what i research and saw are mostly
promises within promises or callbacks within callbacks.
what i want is if i can rereplicate what was shown as per below ( python )
def f(x):
return x+1
var1 = 5
var1 = f(var1)
# var1 is now 6
which is bringing callbacks / promises / async await variable out of its own function rather than
var IP = GetIpAddress().then((IP) => {
requester.connect('tcp://127.0.0.1:5433');
console.log('Worker connected to port 5433');
requester.on('message', function (msg) {
// arr = str.split(",");
console.log(msg.toString());
});
requester.send(
`${IP}:${PORT}`
);
console.log(`${IP}:${PORT}`);
});

Change:
var IP = GetIpAddress();
console.log(`${IP}:${PORT}`);
to:
GetIpAddress().then((IP) => {
console.log(`${IP}:${PORT}`);
}
);
You can read 6 Reasons Why JavaScript’s Async/Await Blows Promises Away (Tutorial)
Update:
Option 1 put everything in the then:
GetIpAddress().then((IP) => {
requester.connect('tcp://127.0.0.1:5433');
console.log('Worker connected to port 5433');
requester.on('message', function (msg) {
// arr = str.split(",");
console.log(msg.toString());
});
requester.send(
`${IP}:${PORT}`
);
console.log(`${IP}:${PORT}`);
});
Option 2 is to wrap everything in an async function:
async function hi(){
var a = await GetIpAddress();
console.log(a);
}
hi();
Option 2 is the one I would opt for as it provides a cleaner way of writing things.

you need to add await before the method call. the main method also need to async.
var IP = await GetIpAddress();
try to use
new promise(function (accept, reject){ // if Ip found
accept("ipaddress") //else reject("error log")
}).then(function(response){ // this is accept , print IPaddress
}).catch(function(err){ // this is reject. } );

Related

NodeJS - return response as a process continue working anyways

I have an async method which invokes a few calls (await promise....) in a loop,
and eventually returns a result.
When I get the result from that function, I send back a response to the client.
What I have to do is to return a response in the middle of the process/loop,
while the loop continue running.
Of course it breaks the loop, since it returns from the function in the middle of the loop.
Here is a piece of code to demonstrate.
app.post('/test', async (req, res)=>{
const body = JSON.stringify(req.body)
await doSomething()
res.status(200).send("ok");
});
const doSomething = async () => {
let times = 0;
for(let i=0 ; i<5 ; i++){
console.log(i)
await delay(1000);
if(i==2){
return 2;
}
}
return times;
}
const delay = async (ms) => {
return await new Promise(resolve => setTimeout(resolve, ms));
}
When I get i==2, I want to return a value and response to the client,
but I still want the loop to run till the end.
I thought to use some observer which will be responsible for returning a response,
(say rxjs, event emitter, etc...). Not sure what is the best practice for such
a different situation.
Thanks for any advice.
The solution is to use a synchronous function and return a Promise. But AFAIK making the callback passed to the Promise constructor async won't work:
const doSomething = () => {
let times = 0;
return new Promise(async (resolveMain) => {
for(let i=0 ; i<5 ; i++){
console.log(i)
await delay(1000);
if(i==2){
resolveMain(2);
}
}
});
}
It's also twisted LOL.
So I'm sure there are many other ways to accomplish this, but I'm assuming you want to keep the await delay(1000);. What you're gong to need is an async generator function.
app.post('/test', async (req, res)=>{
const body = JSON.stringify(req.body)
await doSomething()
res.status(200).send("ok");
});
async function* doLoopyThing(){
let times = 0;
for(let i=0 ; i<5 ; i++){
console.log(i)
await delay(1000);
if(i==2){
yield 2;
}
}
}
function doSomething(){
return new Promise(resolve => {
const looper = doLoopyThing();
looper.next().then(({value}) => resolve(value));
looper.next();
}
}
This is also twisted, but it should work.
I don't understand how this can possibly be the right way to actually accomplish something. But I'm assuming the is just for fun, or you're trying to learn.
Also if all you were trying to show with the await delay(1000) was a heavy function, and you don't actually need the function to be asynchronous, the first solution should work.

function delaying on node.js

Im on a big problem, I need to do an application that gets trello content as soon as i can but i dont know why my for isnt working as it should do. when i the output of this should be the card id and when the function is called it should show the member. I dont know why, but when the 'miembro' function is called, it delays and it is shown after the second id, so its delayed a lot and i need them to show one under the other. I appreciate a quick answer, thank you!
const trelloKB = require("trello-kb");
const fetch = require('node-fetch');
// Replace this by the application key of your Trello account
var appKey = '51501902fff527d305686a29d6d61cfa';
// Replace this by a valid authorization token
var authToken = '9828f5f03073ae52ffdae77bdf49c939df8a315b169cb81aeb42a3d43d0f9e21';
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
function miembros (id){
fetch('https://api.trello.com/1/cards/'+id+'/members?key=51501902fff527d305686a29d6d61cfa&token=9828f5f03073ae52ffdae77bdf49c939df8a315b169cb81aeb42a3d43d0f9e21&fields=fullName', {
method: 'GET'
})
.then(response => {
setTimeout(function() {
return(response.text());
}, 3000);
})
.then(text => console.log(text))
.catch(err => console.error(err));
}
trelloKB.get(appKey, authToken, '33CP31Sf').then(
function (cards) {
// Print the title of each card
var ms = 3000;
for(i=0; i<2; i++){
var card = cards[0];
var id = card.id;
var titleCard = card.title;
console.log(id);
miembros(id);
}
},
);
I think you should learn about synchronous and asynchronous concept
You need to use async-await and return a promise in your function miembros()
read this async await and promise.
this is my example
const cards =[{id:1,title:'kimiwo'},{id:2,title:'namae wa'},{id:3,title:'udiiiin'}];
yourname(cards);
async function yourname (cards) {
for(let card of cards){
console.log(`id :${card.id},text:${card.title}`);
let result = await(await miembros(card.id)).text();
console.log(result);
}
}
function miembros(id){
return fetch('https://api.trello.com/1/cards/'+id+'/members?key=51501902fff527d305686a29d6d61cfa&token=9828f5f03073ae52ffdae77bdf49c939df8a315b169cb81aeb42a3d43d0f9e21&fields=fullName')
}
you can see the result here
*Edit
fetch returns promise, so you can just return fetch and wrap your function with async-await
It’s delayed because you need to use a sync await or .then
You need to get the first Id first, then do a .then to get the second ID through the function call.
Also, you shouldn’t show you API keys, they’re supposed to be private lol

NodeJS Await Within Await Unexpected Token [duplicate]

I wrote this code in lib/helper.js:
var myfunction = async function(x,y) {
....
return [variableA, variableB]
}
exports.myfunction = myfunction;
Then I tried to use it in another file :
var helper = require('./helper.js');
var start = function(a,b){
....
const result = await helper.myfunction('test','test');
}
exports.start = start;
I got an error:
await is only valid in async function
What is the issue?
The error is not refering to myfunction but to start.
async function start() {
....
const result = await helper.myfunction('test', 'test');
}
// My function
const myfunction = async function(x, y) {
return [
x,
y,
];
}
// Start function
const start = async function(a, b) {
const result = await myfunction('test', 'test');
console.log(result);
}
// Call start
start();
I use the opportunity of this question to advise you about an known anti pattern using await which is : return await.
WRONG
async function myfunction() {
console.log('Inside of myfunction');
}
// Here we wait for the myfunction to finish
// and then returns a promise that'll be waited for aswell
// It's useless to wait the myfunction to finish before to return
// we can simply returns a promise that will be resolved later
// useless async here
async function start() {
// useless await here
return await myfunction();
}
// Call start
(async() => {
console.log('before start');
await start();
console.log('after start');
})();
CORRECT
async function myfunction() {
console.log('Inside of myfunction');
}
// Here we wait for the myfunction to finish
// and then returns a promise that'll be waited for aswell
// It's useless to wait the myfunction to finish before to return
// we can simply returns a promise that will be resolved later
// Also point that we don't use async keyword on the function because
// we can simply returns the promise returned by myfunction
function start() {
return myfunction();
}
// Call start
(async() => {
console.log('before start');
await start();
console.log('after start');
})();
Also, know that there is a special case where return await is correct and important : (using try/catch)
Are there performance concerns with `return await`?
To use await, its executing context needs to be async in nature
As it said, you need to define the nature of your executing context where you are willing to await a task before anything.
Just put async before the fn declaration in which your async task will execute.
var start = async function(a, b) {
// Your async task will execute with await
await foo()
console.log('I will execute after foo get either resolved/rejected')
}
Explanation:
In your question, you are importing a method which is asynchronous in nature and will execute in parallel. But where you are trying to execute that async method is inside a different execution context which you need to define async to use await.
var helper = require('./helper.js');
var start = async function(a,b){
....
const result = await helper.myfunction('test','test');
}
exports.start = start;
Wondering what's going under the hood
await consumes promise/future / task-returning methods/functions and async marks a method/function as capable of using await.
Also if you are familiar with promises, await is actually doing the same process of promise/resolve. Creating a chain of promise and executes your next task in resolve callback.
For more info you can refer to MDN DOCS.
When I got this error, it turned out I had a call to the map function inside my "async" function, so this error message was actually referring to the map function not being marked as "async". I got around this issue by taking the "await" call out of the map function and coming up with some other way of getting the expected behavior.
var myfunction = async function(x,y) {
....
someArray.map(someVariable => { // <- This was the function giving the error
return await someFunction(someVariable);
});
}
I had the same problem and the following block of code was giving the same error message:
repositories.forEach( repo => {
const commits = await getCommits(repo);
displayCommit(commits);
});
The problem is that the method getCommits() was async but I was passing it the argument repo which was also produced by a Promise. So, I had to add the word async to it like this: async(repo) and it started working:
repositories.forEach( async(repo) => {
const commits = await getCommits(repo);
displayCommit(commits);
});
If you are writing a Chrome Extension and you get this error for your code at root, you can fix it using the following "workaround":
async function run() {
// Your async code here
const beers = await fetch("https://api.punkapi.com/v2/beers");
}
run();
Basically you have to wrap your async code in an async function and then call the function without awaiting it.
The current implementation of async / await only supports the await keyword inside of async functions Change your start function signature so you can use await inside start.
var start = async function(a, b) {
}
For those interested, the proposal for top-level await is currently in Stage 2: https://github.com/tc39/proposal-top-level-await
async/await is the mechanism of handling promise, two ways we can do it
functionWhichReturnsPromise()
.then(result => {
console.log(result);
})
.cathc(err => {
console.log(result);
});
or we can use await to wait for the promise to full-filed it first, which means either it is rejected or resolved.
Now if we want to use await (waiting for a promise to fulfil) inside a function, it's mandatory that the container function must be an async function because we are waiting for a promise to fulfiled asynchronously || make sense right?.
async function getRecipesAw(){
const IDs = await getIds; // returns promise
const recipe = await getRecipe(IDs[2]); // returns promise
return recipe; // returning a promise
}
getRecipesAw().then(result=>{
console.log(result);
}).catch(error=>{
console.log(error);
});
If you have called async function inside foreach update it to for loop
Found the code below in this nice article: HTTP requests in Node using Axios
const axios = require('axios')
const getBreeds = async () => {
try {
return await axios.get('https://dog.ceo/api/breeds/list/all')
} catch (error) {
console.error(error)
}
}
const countBreeds = async () => {
const breeds = await getBreeds()
if (breeds.data.message) {
console.log(`Got ${Object.entries(breeds.data.message).length} breeds`)
}
}
countBreeds()
Or using Promise:
const axios = require('axios')
const getBreeds = () => {
try {
return axios.get('https://dog.ceo/api/breeds/list/all')
} catch (error) {
console.error(error)
}
}
const countBreeds = async () => {
const breeds = getBreeds()
.then(response => {
if (response.data.message) {
console.log(
`Got ${Object.entries(response.data.message).length} breeds`
)
}
})
.catch(error => {
console.log(error)
})
}
countBreeds()
In later nodejs (>=14), top await is allowed with { "type": "module" } specified in package.json or with file extension .mjs.
https://www.stefanjudis.com/today-i-learned/top-level-await-is-available-in-node-js-modules/
This in one file works..
Looks like await only is applied to the local function which has to be async..
I also am struggling now with a more complex structure and in between different files. That's why I made this small test code.
edit: i forgot to say that I'm working with node.js.. sry. I don't have a clear question. Just thought it could be helpful with the discussion..
function helper(callback){
function doA(){
var array = ["a ","b ","c "];
var alphabet = "";
return new Promise(function (resolve, reject) {
array.forEach(function(key,index){
alphabet += key;
if (index == array.length - 1){
resolve(alphabet);
};
});
});
};
function doB(){
var a = "well done!";
return a;
};
async function make() {
var alphabet = await doA();
var appreciate = doB();
callback(alphabet+appreciate);
};
make();
};
helper(function(message){
console.log(message);
});
A common problem in Express:
The warning can refer to the function, or where you call it.
Express items tend to look like this:
app.post('/foo', ensureLoggedIn("/join"), (req, res) => {
const facts = await db.lookup(something)
res.redirect('/')
})
Notice the => arrow function syntax for the function.
The problem is NOT actually in the db.lookup call, but right here in the Express item.
Needs to be:
app.post('/foo', ensureLoggedIn("/join"), async function (req, res) {
const facts = await db.lookup(something)
res.redirect('/')
})
Basically, nix the => and add async function .
"await is only valid in async function"
But why? 'await' explicitly turns an async call into a synchronous call, and therefore the caller cannot be async (or asyncable) - at least, not because of the call being made at 'await'.
Yes, await / async was a great concept, but the implementation is completely broken.
For whatever reason, the await keyword has been implemented such that it can only be used within an async method. This is in fact a bug, though you will not see it referred to as such anywhere but right here. The fix for this bug would be to implement the await keyword such that it can only be used TO CALL an async function, regardless of whether the calling function is itself synchronous or asynchronous.
Due to this bug, if you use await to call a real asynchronous function somewhere in your code, then ALL of your functions must be marked as async and ALL of your function calls must use await.
This essentially means that you must add the overhead of promises to all of the functions in your entire application, most of which are not and never will be asynchronous.
If you actually think about it, using await in a function should require the function containing the await keyword TO NOT BE ASYNC - this is because the await keyword is going to pause processing in the function where the await keyword is found. If processing in that function is paused, then it is definitely NOT asynchronous.
So, to the developers of javascript and ECMAScript - please fix the await/async implementation as follows...
await can only be used to CALL async functions.
await can appear in any kind of function, synchronous or asynchronous.
Change the error message from "await is only valid in async function" to "await can only be used to call async functions".

return value from mariadb in function nodejs

It's my code:
const mariadb = require('mariadb');
var test = async function(){
var ret = "";
await mariadb.createConnection({
host: "localhost",
user: "dave",
connectionLimit: 5,
password: "!##",
database: "db",
rowsAsArray: false
}).then((data)=>{
ret = "test";
});
return ret;
}
console.log(test());
How can I get a return from then using await?
I know that similar questions have been raised in many cases, but I could not find any using mariadb.
Already I can see a few pitfalls, which as beginners you will come across in this code:
avait is waiting for results to be returned, as he will get Promisses to solve it
then solves promises asynchronously
function defined as async always returns promises
After a moment of delight, 'async / await' now I try to avoid him. Mainly because every function in which I use the asynchronous function must also be asynchronous until you use then, eg make small test:
let test = async function() {
let x = await 11
return 1;
}
console.log(test()) //returns: Promise { <pending> }
There is nothing asynchronous there, but adding async / await has caused a mess.
Now fixes for your code
const mariadb = require('mariadb');
// use local scope `let` instead global `var`
let test = async function(){
let conn = await mariadb.createConnection({
host: "localhost",
user: "dave",
connectionLimit: 5,
password: "!##",
database: "db",
rowsAsArray: false
});
return conn.query("SELECT 1 as val") // no sense using `avait` because `test()` returns `promise`
}
test().then(function(rows) { console.log(rows)});
and without asnc. then can return promise and this can be resolbed by next then
mariadb.createConnection(...).then(conn => { // create connection
return conn.query("SELECT 1 as val") // make query
}).then(rows => { //get result
console.log(rows)
}).catch(err => console.error(err)) // get errors
By the way: get interested in query builder, for example knex.js. It allow write code independent from database engine.
Update
Let's start with the fact that Node is based on events.
Let's take an example of receiving data from the database. In PHP / C ++, you make an query, wait, receive a result. And this behavior simulates by the await. (Await appeared somewhere near version 8)
Normally, the code in the Node works so that you execute the query, and Node creates a new thread. Old run next instruction, in new you will get the results. (OK, I'm lying, but it's easier to explain).
So, you have to handle the event of receiving the data. And more specifically the promise of providing data. By await,.then (), orcallback (hell)
first code explanation:
You try return ret, but this code first make return ret and after make assigment.
await "returns" data, so you should use let var_name = await asyncFunction()
I'm guess, that you want this:
let getSomeDataFromDB = function(){
return mariadb.createConnection([skip]).then(conn => {
return conn.query("SELECT 1 as val")
})
}
let rows = await getSomeDataFromDB()
In this function you return promise, who return promise. And by await this promise chain is resolved.
But here is a "small" error in the code. Because you are connecting and you are not ending your connection anywhere. Therefore, it is better to have a global connection object, or use something like this:
let getSomeDataFromDB = function(){
return new Promise(function(resolve, reject){
mariadb.createConnection([skip]).then(conn => {
conn.query("SELECT 1 as val")
.then(rows=>resolve(rows))
.catch(e=>reject(e))
.then(()=>conn.close())
}).catch(e => reject(e))
})
}
let rows = await getSomeDataFromDB()
And here you discover another important thing: resolve does not interrupt the execution of the code. Despite the data being returned to the user, you can still do something.
Or the same with await
let getSomeDataFromDB = async function(){
let conn = await reateConnection([skip])
let rows = await conn.query("SELECT 1 as val")
await conn.close();
return rows;
}
let rows = await getSomeDataFromDB()

How to use loops in promises

I'm trying to execute a for loop within a promise with no success, i think my issue has to do with where to call resolve but i'm not sure
/*
* Get conversations of user
* #param user {String}
*/
function getConversations(user){
return new Promise(function(resolve, reject){
var conversations = user.Conversations
var newConversations = []
for(var conversation of conversations) {
helperGetConvo(conversation.ConversID).then(function(convo){
newConversations.push(createConversationObject({messages:[], name:convo.conversationName, users:["broulaye", "doumbia"], Id:convo.conversationID}))
}).catch(function(reason) {
console.log("failure when finding conversation 2: " + reason)
})
}
resolve(newConversations)
})
}
function helperGetConvo(convoId) {
return new Promise (function(resolve, reject){
query.findConversation(convoId).then(function(convers) {
if(convers) {
console.log("conversation was found: " + convers)
}
else {
console.log("conversation was not found: " + convers)
}
resolve(convers)
}).catch(function(reason) {
console.log("failure when finding conversation: " + reason)
})
})
}
when I execute my code like this the getConversations function only returns an empty array. but when i change the getConversations function like so:
function getConversations(user){
return new Promise(function(resolve, reject){
var conversations = user.Conversations
var newConversations = []
for(var conversation of conversations) {
helperGetConvo(conversation.ConversID).then(function(convo){
newConversations.push(createConversationObject({messages:[], name:convo.conversationName, users:["broulaye", "doumbia"], Id:convo.conversationID}))
resolve(newConversations)
}).catch(function(reason) {
console.log("failure when finding conversation 2: " + reason)
})
}
})
}
i do get an output, however it does not get through the whole forloop i believe because from my understanding resolve work like a return statement.
someone help plz
You need to use Promise.all
function getConversations(user){
var conversations = user.Conversations
var promises = conversations.map(c=>helperGetConvo(c.ConversID))
return Promise.all(promises)
.then(data=>{
let newConversations = data.map(convo=>{
return createConversationObject({messages:[], name:convo.conversationName, users:["broulaye", "doumbia"], Id:convo.conversationID})
})
return newConversations
})
.catch(reason=>{
console.log("failure when finding conversation: " + reason)
})
}
Use the function like so
getConversations(user).then(newConversations=>{
//your code
})
One way is to collect the promises in an array using map instead of for-in. Then use Promise.all() to wait for all of them to resolve (or one to reject).
Something like:
return Promise.all(conversations.map(conversation => {
return helperGetConvo(...).then().catch();
}
Remember all promises MUST either resolve or reject. If you don't follow this rule you get into trouble.
You can loop a promise within a helper function that I found when I was trying to address a similar issue. I use this method to loop promises as it will not fall over at the first rejected promise. Instead I can handle the resolve or reject and return the final result once the loop has finished. The Promise in the code snippet below is using bluebird, http://bluebirdjs.com/docs/getting-started.html
function promiseWhile(condition, action) {
return new Promise((resolve, reject) => {
var loop = () => {
if (!condition()) return resolve();
return Promise.cast(action())
.then(loop)
.catch(reject);
};
process.nextTick(loop);
return resolve;
})
}
I modified your code examples provided with some dummy data and got it to work with the helper function. As a result I believe your getConversations function would look like this:
function getConversations(user) {
var conversations = user.Conversations;
var newConversations = [];
var stop = conversations.length;
var index = 0
//loop promise
return promiseWhile(() => {
// Condition for stopping
return index < stop;
}, () => {
// Action to run, should return a promise
return new Promise((resolve, reject) => {
helperGetConvo(conversations[index].ConversID)
.then(function(convo) {
newConversations.push(createConversationObject({
messages: [],
name: convo.conversationName,
users: ['broulaye', 'doumbia'],
Id: convo.conversationID
}));
index++;
resolve();
})
.catch((error) => {
console.log('failure when finding conversation: ' + error);
index++;
resolve();
});
})
})
//This will execute when loop ends
.then(() => {
return newConversations;
});
}
Hope this helps.
The problem is that when you call resolve you are resolving the entire promise. The for loop does not wait for each helperGetConvo() call to finish before moving on to the next one. Whichever of those promises hits the then statement first will call resolve and that's what your outer promise will resolve to.
You can read more on promises at: Understanding promises in node.js.
If you want to wait for a group of promises to finish, use Promise.all. It takes in a list of promises, and will only resolve if all promises complete successfully.
function getConversations(user) {
return new Promise(function (resolve, reject) {
var conversations = user.Conversations;
var newConversations = [];
//create a list of promises
var promises = [];
for (var conversation of conversations) {
// push each promise into our array
promises.push(
helperGetConvo(conversation.ConversID).then(function (convo) {
newConversations.push(createConversationObject({
messages: [],
name: convo.conversationName,
users: ['broulaye', 'doumbia'],
Id: convo.conversationID
}));
}).catch(function (reason) {
console.log('failure when finding conversation 2: ' + reason);
})
);
}
// wait for all promises to complete
// when then do, resolve the newConversations variable
// which will now have all of the conversation objects that we wanted to create
Promise.all(promises).then(() => resolve(newConversations)).catch(reject);
});
}
You could also use async/await to clean this up. Async/await provides some nice syntactic sugar for removing the need to do return new Promise(...). This next code snippet is not the best way to use async/await because the for loop will process everything synchronously (one conversation at a time). This blog post has been hugely helpful for my understanding of using async/await in iterative problems: https://blog.lavrton.com/javascript-loops-how-to-handle-async-await-6252dd3c795.
async function getConversations(user) {
var conversations = user.Conversations;
var newConversations = [];
// process each converstaion in sequence
for (var conversation of conversations) {
// instead of doing .then() we can use await
// convo will have the result from the helperGetConvo
// we put it in a try/catch because output
// we still want to have the error if something fails
try {
var convo = await helperGetConvo(conversation.ConversID);
newConversations.push(createConversationObject({
messages: [],
name: convo.conversationName,
users: ['broulaye', 'doumbia'],
Id: convo.conversationID
}));
} catch(reason) {
console.log('failure when finding conversation 2: ' + reason);
}
}
// return
return newConversations;
}
Async functions return promises. So you can call this function by doing getConversations(user).then(...). But I think async/await makes your code look much cleaner. There are definitely further optimizations that you can do, but hopefully this gets you started.

Resources