Async Function returns promise - javascript

I have a function that returns the guilds prefix in Discord.JS:
getprefix.js:
const GuildSchema = require("../Database/Models/GuildConfigs");
const { DEFAULT } = require("./config");
const getprefix = async (id) => {
const guildConfigs = await GuildSchema.findOne({
GuildID: id,
});
let PREFIX = DEFAULT;
if (guildConfigs && guildConfigs?.Prefix) {
PREFIX = guildConfigs?.Prefix;
}
};
module.exports = { getprefix };
I call the function in another file using this:
let prefix = getprefix(message.guild.id);
prefix.then(() => {
console.log(prefix);
});
The problem is it returns this in the console:
Promise { '!' }
Is it possible to just return the actual prefix that is inside the quotes with out the Promise?

Yes, but you must return the value from the async function.
getprefix.js:
const GuildSchema = require("../Database/Models/GuildConfigs");
const { DEFAULT } = require("./config");
const getprefix = async (id) => {
const guildConfigs = await GuildSchema.findOne({
GuildID: id,
});
let PREFIX = DEFAULT;
if (guildConfigs && guildConfigs?.Prefix) {
PREFIX = guildConfigs?.Prefix;
}
return PREFIX;
};
module.exports = { getprefix };
and change the call:
let prefix = getprefix(message.guild.id);
prefix.then((value) => {
console.log(value);
});

First you must return a value from your async function called getprefix. Secondly you must console.log the result of the promise returned by getprefix function instead of the promise itself :
const getprefix = async (id) => {
const guildConfigs = await GuildSchema.findOne({GuildID: id});
if (!guildConfigs || !guildConfigs.Prefix) {
return DEFAULT;
}
return guildConfigs.Prefix;
};
getprefix(message.guild.id).then(prefix => console.log(prefix));

Related

Node.js fs.access returns undefined no matter what

Here's the code:
import * as path from 'path';
import * as fs from 'fs';
const doesPathExist = async (path: string) => {
return await fs.access(path, fs.constants.R_OK, (err) => {
return err ? false : true;
});
};
const someFunc = async (documentName: string) => {
const documentPath = path.join(__dirname, documentName);
const pathExists = doesPathExist(documentName);
};
The function doesPathExistseems to return Promise<void>, making the pathExists variable undefined no matter the outcome. I've tried initializing a temp variable at the top of the function before running fs.access and changing its value inside the callback but still no luck.
The issue is with fs.access, this function does not return a Promise or anything else.
There are a few options to solve it.
you can always use fs.accessSync()
const doesPathExist = async (path: string) => {
try {
fs.accessSync(path, fs.constants.R_OK)
return true
} catch (e) {
return false
}
};
Use fs.promises
const fsPromises = fs.promises;
const doesPathExistB = async (path: string) => {
try {
await fsPromises.access(path, fs.constants.R_OK)
return true
} catch (e) {
return false
}
};
// OR
const doesPathExistA = async (path: string) => {
return new Promise(async (resolve) => {
await fsPromises.access(path, fs.constants.R_OK)
.then(() => resolve(true))
.catch(() => resolve(false))
})
};

chained await in class chained methods

context: Two javascript classes in separate files, each integrating a different external service and being called in a express.js router.
See "problematic code" below:
route
routes.post('/aws', upload.single('file'), async (req, res) => {
const transcribeParams = JSON.parse(req.body.options)
const bucket = 'bucket-name'
const data = await ( await ( await awsTranscribe.Upload(req.file, bucket)).CreateJob(transcribeParams)).GetJob()
res.send(data)
})
S3 class
class AmazonS3 {
constructor() {
this.Upload = this.Upload
}
async Upload(file, bucket) {
const uploadParams = {
Bucket: bucket,
Body: fs.createReadStream(file.path),
Key: file.filename,
}
this.data = await s3.upload(uploadParams).promise()
return this
}
}
Transcribe class
class Transcribe extends AwsS3 {
constructor() {
super()
this.CreateJob = this.CreateJob
this.GetJob = this.GetJob
}
async CreateJob(params) {
if(this.data?.Location) {
params.Media = { ...params.Media, MediaFileUri: this.data.Location }
}
this.data = await transcribeService.startTranscriptionJob(params).promise()
return this
}
async GetJob(jobName) {
if(this.data?.TranscriptionJob?.TranscriptionJobName) {
jobName = this.data.TranscriptionJob.TranscriptionJobName
}
this.data = await transcribeService.getTranscriptionJob({TranscriptionJobName: jobName}).promise()
return this
}
}
problem: the problem is with the chained awaits in the router file:
await ( await ( await awsTranscribe.Upload...
Yes, it does work, but it would be horrible for another person to maintain this code in the future.
How can i make so it would be just
awsTranscribe.Upload(req.file, bucket).CreateJob(transcribeParams).GetJob() without the .then?
The problem is with the chained awaits in the router file: await ( await ( await awsTranscribe.Upload...
No, that's fine. In particular it would be trivial to refactor it to separate lines:
routes.post('/aws', upload.single('file'), async (req, res) => {
const transcribeParams = JSON.parse(req.body.options)
const bucket = 'bucket-name'
const a = await awsTranscribe.Upload(req.file, bucket);
const b = await b.CreateJob(transcribeParams);
const c = await b.GetJob();
res.send(c);
});
Your actual problem is that a, b, and c all refer to the same object awsTranscribe. Your code would also "work" if it was written
routes.post('/aws', upload.single('file'), async (req, res) => {
const transcribeParams = JSON.parse(req.body.options)
const bucket = 'bucket-name'
await awsTranscribe.Upload(req.file, bucket);
await awsTranscribe.CreateJob(transcribeParams);
await awsTranscribe.GetJob();
res.send(awsTranscribe);
});
The horrible thing is that you are passing your data between these methods through the mutable awsTranscribe.data property - even storing different kinds of data in it at different times! One could change the order of method calls and it would completely break in non-obvious and hard-to-debug ways.
Also it seems that multiple requests share the same awsTranscribe instance. This will not work with concurrent requests. Anything is possible from just "not working" to responding with the job data from a different user (request)! You absolutely need to fix that, then look at ugly syntax later.
What you really should do is get rid of the classes. There's no reason to use stateful objects here, this is plain procedural code. Write simple functions, taking parameters and returning values:
export async function uploadFile(file, bucket) {
const uploadParams = {
Bucket: bucket,
Body: fs.createReadStream(file.path),
Key: file.filename,
};
const data = s3.upload(uploadParams).promise();
return data.Location;
}
export async function createTranscriptionJob(location, params) {
params = {
...params,
Media: {
...params.Media,
MediaFileUri: location,
},
};
const data = await transcribeService.startTranscriptionJob(params).promise();
return data.TranscriptionJob;
}
async function getTranscriptionJob(job) {
const jobName = job.TranscriptionJobName;
return transcribeService.getTranscriptionJob({TranscriptionJobName: jobName}).promise();
}
Then you can import and call them as
routes.post('/aws', upload.single('file'), async (req, res) => {
const transcribeParams = JSON.parse(req.body.options)
const bucket = 'bucket-name'
const location = await uploadFile(req.file, bucket);
const job = await createTranscriptionJob(location, transcribeParams);
const data = await getTranscriptionJob(job);
res.send(c);
});
I got interested in whether it was possible to take an object with several async methods and somehow make them automatically chainable. Well, you can:
function chain(obj, methodsArray) {
if (!methodsArray || !methodsArray.length) {
throw new Error("methodsArray argument must be array of chainable method names");
}
const methods = new Set(methodsArray);
let lastPromise = Promise.resolve();
const proxy = new Proxy(obj, {
get(target, prop, receiver) {
if (prop === "_promise") {
return function() {
return lastPromise;
}
}
const val = Reflect.get(target, prop, receiver);
if (typeof val !== "function" || !methods.has(prop)) {
// no chaining if it's not a function
// or it's not listed as a chainable method
return val;
} else {
// return a stub function
return function(...args) {
// chain a function call
lastPromise = lastPromise.then(() => {
return val.apply(obj, args);
//return Reflect.apply(val, obj, ...args);
});
return proxy;
}
}
}
});
return proxy;
}
function delay(t) {
return new Promise(resolve => {
setTimeout(resolve, t);
});
}
function log(...args) {
if (!log.start) {
log.start = Date.now();
}
const delta = Date.now() - log.start;
const deltaPad = (delta + "").padStart(6, "0");
console.log(`${deltaPad}: `, ...args)
}
class Transcribe {
constructor() {
this.greeting = "Hello";
}
async createJob(params) {
log(`createJob: ${this.greeting}`);
return delay(200);
}
async getJob(jobName) {
log(`getJob: ${this.greeting}`);
return delay(100);
}
}
const t = new Transcribe();
const obj = chain(t, ["getJob", "createJob"]);
log("begin");
obj.createJob().getJob()._promise().then(() => {
log("end");
});
There's a placeholder for your Transcribe class that has two asynchronous methods that return a promise.
Then, there's a chain() function that returns a proxy to an object that makes a set of passed in method names be chainable which allows you to then do something like this:
const t = new Transcribe();
// make chainable proxy
const obj = chain(t, ["getJob", "createJob"]);
obj.createJob().getJob()
or
await obj.createJob().getJob()._promise()
I wouldn't necessarily say this is production-ready code, but it is an interesting feasibility demonstration and (for me) a chance to learn more about a Javascript proxy object.
Here's a different approach that (instead of the proxy object) adds method stubs to a promise to make things chainable:
function chain(orig, methodsArray) {
let masterP = Promise.resolve();
function addMethods(dest) {
for (const m of methodsArray) {
dest[m] = function(...args) {
// chain onto master promise to force sequencing
masterP = masterP.then(result => {
return orig[m].apply(orig, ...args);
});
// add methods to the latest promise befor returning it
addMethods(masterP);
return masterP;
}
}
}
// add method to our returned promise
addMethods(masterP);
return masterP;
}
function delay(t) {
return new Promise(resolve => {
setTimeout(resolve, t);
});
}
function log(...args) {
if (!log.start) {
log.start = Date.now();
}
const delta = Date.now() - log.start;
const deltaPad = (delta + "").padStart(6, "0");
console.log(`${deltaPad}: `, ...args)
}
class Transcribe {
constructor() {
this.greeting = "Hello";
this.cntr = 0;
}
async createJob(params) {
log(`createJob: ${this.greeting}`);
++this.cntr;
return delay(200);
}
async getJob(jobName) {
log(`getJob: ${this.greeting}`);
++this.cntr;
return delay(100);
}
}
const t = new Transcribe();
log("begin");
chain(t, ["getJob", "createJob"]).createJob().getJob().then(() => {
log(`cntr = ${t.cntr}`);
log("end");
});
Since this returns an actual promise (with additional methods attached), you can directly use .then() or await with it without the separate ._promise() that the first implementation required.
So, you can now do something like this:
const t = new Transcribe();
chain(t, ["getJob", "createJob"]).createJob().getJob().then(() => {
log(`cntr = ${t.cntr}`);
});
or:
const t = new Transcribe();
await chain(t, ["getJob", "createJob"]).createJob().getJob();
log(`cntr = ${t.cntr}`);
And, here's a third version where it creates a thenable object (a pseudo-promise) with the added methods on it (if it bothers you to add methods to an existing promise):
function chain(orig, methodsArray) {
if (!methodsArray || !methodsArray.length) {
throw new Error("methodsArray argument must be array of chainable method names");
}
let masterP = Promise.resolve();
function makeThenable() {
let obj = {};
for (const m of methodsArray) {
obj[m] = function(...args) {
// chain onto master promise to force sequencing
masterP = masterP.then(result => {
return orig[m].apply(orig, ...args);
});
return makeThenable();
}
}
obj.then = function(onFulfill, onReject) {
return masterP.then(onFulfill, onReject);
}
obj.catch = function(onReject) {
return masterP.catch(onReject);
}
obj.finally = function(onFinally) {
return masterP.finally(onFinally);
}
return obj;
}
return makeThenable();
}
function delay(t) {
return new Promise(resolve => {
setTimeout(resolve, t);
});
}
function log(...args) {
if (!log.start) {
log.start = Date.now();
}
const delta = Date.now() - log.start;
const deltaPad = (delta + "").padStart(6, "0");
console.log(`${deltaPad}: `, ...args)
}
class Transcribe {
constructor() {
this.greeting = "Hello";
this.cntr = 0;
}
async createJob(params) {
log(`createJob: ${this.greeting}`);
++this.cntr;
return delay(200);
}
async getJob(jobName) {
log(`getJob: ${this.greeting}`);
++this.cntr;
return delay(100);
}
}
const t = new Transcribe();
log("begin");
chain(t, ["getJob", "createJob"]).createJob().getJob().then(() => {
log(`cntr = ${t.cntr}`);
log("end");
});

How do i run a replace function in async function?

I had a MongoDB and I want to change a value of a bunch of templates.
I guess I get the variable and replace the old value.
findTemplates.forEach(async templateName => {
const template = await getTemplate( templateName )
const templateBody = await replaceBody( template.body )
templateBody.replace('string', 'another-string');
})
async function getTemplate (siteName) {
const id = await emailTemplate.model.findOne({
'name.de': siteName,
language: 'en',
businessUnit: '24ede462ad78fd0d4fd39dfa',
}).distinct('_id')
const body = await emailTemplate.model.findOne({
'_id': id,
}).distinct('body')
return {
id: id,
body: body
}
}
function replaceBody( body ) {
return body.replace('one', 'two')
}
unfortunately, I get the following error:
UnhandledPromiseRejectionWarning: TypeError: body.replace is not a functiontemplateBodyHow can I use the replace function in my forEach async function?
I rewrote your sample, so I can simulate it, this sample works as you expected, but no exception was thrown. So, the only mistake I have detected was in this line:
// You must not put await here because replace body does not return a Promise.
const templateBody = replaceBody( template.body )
const allTemplates = []
for (let i = 0; i <= 10; i++) {
allTemplates.push({
_id: faker.random.uuid(),
'name.de': faker.internet.domainName(),
language: faker.random.locale(),
businessUnit: faker.random.uuid(),
body: faker.lorem.paragraph()
})
}
const findTemplates = allTemplates.map(item => item['name.de'])
const emailTemplate = {
model: {
findOne: params => {
const found = allTemplates.find(item => params._id ? item._id === params._id : item['name.de'] === params['name.de'])
const result = Object.assign({}, found, params)
result.distinct = function (key) {
return Promise.resolve(this[key])
}
return result
}
}
}
async function getTemplate (siteName) {
const id = await emailTemplate.model.findOne({
'name.de': siteName,
language: 'en',
businessUnit: '24ede462ad78fd0d4fd39dfa',
}).distinct('_id')
const body = await emailTemplate.model.findOne({
'_id': id,
}).distinct('body')
return {
id: id,
body: body
}
}
function replaceBody( body ) {
return body.replace('one', 'two')
}
findTemplates.forEach(async templateName => {
try {
const template = await getTemplate( templateName )
// You must not put await here because replace body does not return a Promise.
const templateBody = replaceBody( template.body )
console.log(templateBody.replace('string', 'another-string'))
} catch (err) {
console.err(`Error procesing template: ${templateName}: ${err}`)
}
})
/**
* Alternatively you can do:
Promise.all(findTemplates.map(async templateName => {
const template = await getTemplate( templateName )
// You must not put await here because replace body does not return a Promise.
const templateBody = replaceBody( template.body )
console.log(templateBody.replace('string', 'another-string'))
}).catch(err => console.err)
*/
<script src="https://cdnjs.cloudflare.com/ajax/libs/Faker/3.1.0/faker.min.js"></script>
So respect to your question: How can I use the replace function in my forEach async function? The answer is you can use replace as you do (but fix the line, and check what #t-j-crowder commented).
If the body is not string, then you should inspect what kind of object it is, and if it has a replace function (or not), and if this replace function returns (or not) a Promise.

Can we use await and same functions for promises?

So i have request coming based on that i am building this.request array so i can make calls to urls and request.body that is pushed into array , In below code trying to use RequestResponseHandler.processRequest for both promises but its always going into spec(duplicate call) when i call same function processRequest for other promise , How can i make sure if processRequest is called for spec ignore that if condition and go to PTM
request
{ header: { lineOfBusiness: ["spec","PTM"] } , body: data }
handler.ts
export class RequestResponseHandler {
public static processRequest(data: any, url: string): Promise < any > {
const reqObject: IRequestURL = {}
as IRequestURL;
const lob = data.header.lineOfBusiness;
if (lob[0] === "spec") {
const specUrl = urlConfig + url;
reqObject.url = specUrl;
reqObject.body = data;
}
if (lob[1] === "PTM") {
const ptmUrl = urlConfig + url;
reqObject.url = ptmUrl;
reqObject.body = data;
}
return Promise.resolve(reqObject);
}
}
controllet.ts
const bRetSpec: boolean = await this.specBalanceRequest(request);
const bRetPtm: boolean = await this.ptmBalanceRequest(request);
if (!bRetPtm && !bRetSpec) {
return Promise.reject(new Error("Processing failed"));
}
try {
const __data: IResponse = await makeRequest(this._request);
const resp1 = await another promise to resolve _data[0];
const resp2 = await another promise to resolve _data[1];
return await Promise.all([resp1, resp2]);
} catch (err) {
return Promise.reject(err);
}
private async specBalanceRequest(#Body() request: ExpressRequest): Promise < boolean > {
const specUrl = "/payments";
const reqObject = await RequestResponseHandler.processRequest(request.body, specialtyUrl);
this._request.push(reqObject);
return Promise.resolve(true);
}
private async ptmBalanceRequest(#Body() request: any): Promise < boolean > {
const careURL = "/Order";
const reqObject = await RequestResponseHandler.processRequest(request.body, careURL);
this._request.push(reqObject);
return Promise.resolve(true);
}
One thing that I suggest is to not make unnecessary promise function. Keep it simple as possible.
RequestResponseHandler.processRequest doesn't need to be a promise
export class RequestResponseHandler {
public static processRequest(data: any, url: string): IRequestURL {
const reqObject: IRequestURL = {} as IRequestURL;
const lob = data.header.lineOfBusiness;
// I guess we can improve code below, no diff between "spec" and "ptm"
if (lob[0] === "spec") {
const specUrl = urlConfig + url;
reqObject.url = specUrl;
reqObject.body = data;
}
if (lob[1] === "PTM") {
const ptmUrl = urlConfig + url;
reqObject.url = ptmUrl;
reqObject.body = data;
}
return reqObject; // return value not a promise
}
}
in controller file
const bRetSpec: boolean = this.specBalanceRequest(request); // remove `await`
const bRetPtm: boolean = this.ptmBalanceRequest(request); // remove `await`
if (!bRetPtm && !bRetSpec) {
return Promise.reject(new Error("Processing failed"));
}
try {
const __data: IResponse = await makeRequest(this._request);
// the two promise calls, I guess can be move to be inside promise.all
return await Promise.all([anotherPromiseData0, anotherPromiseData1]);
} catch (err) {
return Promise.reject(err);
}
// make it non promise
private specBalanceRequest(#Body() request: ExpressRequest): void {
const specUrl = "/payments";
const reqObject = RequestResponseHandler.processRequest(request.body, specialtyUrl);
this._request.push(reqObject);
}
// make it non promise
private ptmBalanceRequest(#Body() request: any): void {
const careURL = "/Order";
const reqObject = RequestResponseHandler.processRequest(request.body, careURL);
this._request.push(reqObject);
}

Why I am getting undefined after calling fetchNotes

After calling fetchNotes from the addNote function it shows me undefined as push method is not defined in the addNote function
const fs = require('fs');
const fetchNotes = ()=>{
fs.readFile('data.json',(err,notes)=>{
if(err){
// return empty array if data.json not found
return [];
}else{
// return Object from data found data.json file
return JSON.parse(notes)
}
});
}
const saveNotes = (notes) =>{
fs.writeFile('data.json',JSON.stringify(notes),()=>{
console.log('Notes is successfully saved');
});
}
const addNote = (title, body)=>{
const note = {
title,
body
}
const notes = fetchNotes();
//Push method not defined
notes.push(note);
saveNotes(notes);
return note;
}
module.exports.addNote = addNote;
It returns undefined because when you are returning in the callback you are not exactly returning from the fetchNotes function itself.
Maybe you can use the readFileSync and don't use callback or maybe you can make it a promise and use async/await
const fetchNotes = () => {
return new Promise((res, rej) => {
fs.readFile('data.json', (err, notes) => {
if (err) {
// return empty array if data.json not found
res([]);
} else {
// return Object from data found data.json file
res(JSON.parse(notes));
}
});
});
}
const addNote = async (title, body) => {
const note = {
title,
body
}
const notes = await fetchNotes();
//Push method not defined
notes.push(note);
saveNotes(notes);
return note;
}
Alternatively, you can use utils.promisify
return JSON.parse(notes) does not store this value inside fetchNotes because it is asynchronous, so you get the content of the file later in time.
To do it asynchronously, you can use async/await :
const fetchNotes = () => {
return new Promise((resolve, reject) => {
fs.readFile('data.json', (err,notes) => resolve(JSON.parse(notes)));
})
}
const addNote = async (title, body) => {
// ...
const notes = await fetchNotes();
notes.push(note);
saveNotes(notes);
return note;
}
You can also do it synchronously :
const fetchNotes = () => JSON.parse( fs.readFileSync('data.json') );
const notes = fetchNotes();

Categories