Reputation: 630
Very much a nodejs noob, trying to make sense of promises, await, async. I promise you I did my due diligence research (spent the entire day studying to get the code hereunder. I'm still not entirely sure everything is as it should be and can find no reference that has the exact same thing (or close enough) to what I'm trying to do here.
Thanks for any help.
General structure:
function msg() is waiting for 4 functions to complete, the 4 api calls (code only shows one): function redditPromise().
redditPromise() calls async function redditGet() -> that's the one that will call reddit API and in the meantime save the API data to database. (function saveToDb())
var nodeSocialApi = require('node-social-api');
var Socstat = require('../proxy').Socstat;
exports.index = function (req, res, next) {
/* SAVES DATA TO MONGODB */
function saveToDb(website,total) {
//** Start : NewAndSave
Socstat.newAndSave(website, total, "random", function (err, socstat) { // newAndSave -> proxy/socstat.js
if (err) {
return next(err);
}
});
//** End : NewAndSave
}
/* END SAVES DATA TO MONGODB */
/* GET DATA FROM REDDIT API */
const reddit = new nodeSocialApi.Reddit(); // no auth needed
async function redditGet() {
let result;
await reddit.get('r/about/about.json')
.then((data) => {
// callback value for promise
result = data.data.subscribers;
saveToDb("reddit",result);
}) // end then
.catch(err => console.log(err));
return result;
}
/* END : GET DATA FROM REDDIT API */
/* REDDIT PROMISE (all the others look the same) */
function redditPromise() {
return new Promise(resolve => {
resolve(redditGet());
});
}
/* END : REDDIT PROMISE (all the others look the same) */
/* ONE FUNCTION THAT WAITS FOR ALL PROMISED FUNCTIONS */
async function msg() {
const [a, b, c,d] = await Promise.all([githubPromise(), twitterPromise(), redditPromise(), facebookPromise()]);
console.log(a + " " + b + " " + c + d);
}
/* END: ONE FUNCTION THAT WAITS FOR ALL PROMISED FUNCTIONS */
msg();
}; // END exports
Upvotes: 1
Views: 4631
Reputation: 39270
The only function available in the code you posted is twitterPromise, I would suggest as Bergi to return promises:
const saveToDb = (website,total) =>
//** Start : NewAndSave
new Promise(
(resolve,reject) =>
Socstat.newAndSave(
website,
total,
"random",
(err, socstat) => // newAndSave -> proxy/socstat.js
(err)
? reject(err)
: resolve(socstat)
)
);
//redditGet does not deal with errors,
// the caller has to deal with the errors (rejected promise)
const redditGet = async () => {
const data = await reddit.get('r/about/about.json');
await saveToDb("reddit",data.data.subscribers);
//just return a promise:
return data.data.subscribers;
};
//facebookGet does not deal with errors,
// the caller has to deal with the errors (rejected promise)
const facebookGet = async () => {
const response = await facebook.get('1118720888180564/fields=fan_count');
console.log(response.fan_count);
const dbResult = await saveToDb("facebook",response.fan_count)
console.log("db entry succesfull -> " + dbResult);
return response.fan_count;
};
//msg does not deal with errors, the caller of msg does
const msg = () =>
Promise.all([githubPromise(), twitterPromise(), redditPromise(), facebookPromise()])
//calling msg and dealing with the error and result
msg()
.then(
results =>
console.log("got resullts",results)
,reject =>
console.error("rejected",reject)
);
If you understand promises you could investigate async await, it has an easier syntax for people used to sync script (try catch) but in the end it will return a promise.
Upvotes: 2
Reputation: 630
Hoping I'm doing right by writing this as a new "answer". Basically just want to show that I'm not taking the help here for granted. Been working hard to pay my dues.
Based on the comments (@HMR) I tried converting some of my functions to async/await. I guess I'm not certain about 2 things: 1) is my final return response.fan_count waiting for the saveToDb to complete? I tried putting return response.fan_count inside the saveToDb.then promise, but that did not work. 2) Should I convert my saveToDb.then() structure to an async/await aswell ?
const facebookGet = async () => {
facebookGet () {
//just return a promise:
let response; // outside to be able to return in the end
try {
response = await facebook.get('1118720888180564/fields=fan_count');
console.log(response.fan_count);
saveToDb("facebook",response.fan_count)
.then(dbResult => {
console.log("db entry succesfull -> " + dbResult); // returns the database object
})
.catch(err => console.error(err));
}
catch (err) {
console.log("fetch failed ", err);
}
return response.fan_count;
}
Answering my own question 1)
putting a "return" before "saveToDb" ... allows me to write "return response.fan_count" inside the ".then"
Upvotes: 0