nodejs how to use multiple await promises - javascript

how can i use multi promise await in my codes ? when i wanna use second await for second promise it throw an error
function ReadJSONFile() {
return new Promise((resolve, reject) => {
fs.readFile('import.json', 'utf-8', (err, data) => {
if (err) reject(err);
resolve(JSON.parse(data));
});
});
}
const Get_Image = async (Path) => {
Child_Process = exec('node get_image.js "'+Path+'",(err,stdout,stderr) =>
return new Promise((resolve,reject) => {
resolve(stdout);
});
}
const Catch = async () => {
let get_json_file = await ReadJSONFile(); // this works perefectly
for(var i=0;i< Object.keys(get_json_file);i++) {
console.log(await Get_Image(get_json_file[i].image_path); //but this throw error
}
}

you didn`t return a promise that is why you got an error
const Get_Image = async (Path) => {
return new Promise((resolve,reject) => {
Child_Process = exec('node get_image.js "'+Path+'",(err,stdout,stderr) =>
resolve(stdout);
});
});
}

Related

using await within function of backend api

I have the code below:
service.js
module.exports = {
getUser
};
async function getUser({ data }) {
return new Promise((resolve, reject) => {
const id = data["id"];
const doc = await db.collection('users').where('id', '==', id).get();
if (!doc.exists) {
resolve('No such document!');
} else {
resolve(doc.data());
}
});
}
controller.js
async function getUser(req, res, next) {
userService.getUser({ data: req.body }).then(function (val) {
res.json(val);
});
}
This throws an error: SyntaxError: await is only valid in async functions and the top level bodies of modules. How can I retrieve the data from the await in an effective manner?
You can use await only inside async function.
function dummy() {
return new Promise((res, rej) => {
setTimeout(() => {
res(20)
}, 300)
})
}
let val = new Promise(async(resolve, reject) => {
let v = await dummy()
resolve(v)
})
val.then(value => console.log(value))

I'm getting an error when I search the database and I don't know how to solve it

I'm making a request to my database, I set the functions as asynchronous and to wait, but it still returns me undefined or Promise { pending }
how do I just return it when I have the result?
export const getGerente = async (req, res) => {
var query = "SELECT * FROM inventory;"
const r = await select(query)
console.log(r)
return res.json({message:"teste"})
}
export async function select(query) {
var teste = await client.connect(() =>{
client
.query(query)
.then((resultado) => {
console.log('sucess!!');
return resultado.rows
/*
const rows=resultado.rows
rows.map(x =>{
console.log(x.name)
})*/
})
.catch((erro) => {
console.log("erro: " + erro.message);
})
.then((teste) => {
console.log('Finished execution, exiting now');
process.exit();
});
})
}
result: Promise { pending }
I'm calling her for a request
Your select function is not awaiting the client.connect properly.
Try this for select function -
export async function select(query) {
const promisifiedRows = new Promise((resolve, reject) => {
client.connect((err) => {
if (err) {
reject(err); // err in connecting
} else {
console.log('Connected!');
client.query(query, (err, rows) => {
if (err) {
reject(err); // err while exceuting the query
} else {
resolve(rows);
}
});
}
});
});
const rows = await promisifiedRows();
return rows;
}

What is the proper way to use Promise.reject with javascript

I have this following piece of code
new Promise((resolve, reject) => {
resolve(apiRequest(data))
reject(console.log('Error'))
}).then(response)
Both methods (resolve and reject) are being fired but I want to call reject only when something goes wrong.
How can I throw an error if something goes wrong on that case?
I checked that but it seems like I can not use an If statement to do that check.
new Promise((resolve, reject) => {
const printResult = apiRequest(data)
console.log(printResult) //Outputs Promise {<pending>}
resolve(printResult) //Then it works
reject(console.log('Error'))
}).then(response)
What would be the correct approach to reject a promise?
The easiest way would be with an if condition. i.e
new Promise((resolve, reject) => {
// do something...
if(somethingGoodHappened) {
resolve(data)
} else {
reject(error)
}
})
But usually when dealing with async requests, the thing you are calling will often be returning a promise, so you can attach the then and catch callbacks there.
apiRequest(data)
.then((result) => {
// all good
})
.catch((err) => {
console.log(err)
})
const mock_api = () => new Promise((res, rej) => {
const number = Math.floor((Math.random() * 100) + 1);
setTimeout(() => {
if (number%2==0) return res('randomly RESOLVED')
return rej('randomly REJECTED')
}, 2000)
})
const async_promise = () => new Promise(async (resolve, reject) => {
try {
const resolvedPromise = await mock_api()
resolve(resolvedPromise)
} catch (e) {
reject(e)
}
})
const classicPromise = () => new Promise((resolve, reject) => {
mock_api()
.then(resolve)
.catch(reject)
})
const makeAsyncRequest = async () => {
try {
const data = await async_promise()
console.log('ASYNC AWAIT RESOLVE', data)
} catch (e) {
console.log('ASYNC AWAIT ERR', e)
}
}
makeAsyncRequest()
classicPromise()
.then(r => console.log('PROMISE CHAIN RESOLVE', r))
.catch(e => console.log('PROMISE CHAIN ERR', e))
Because of you resolve before reject so it cannot run into reject,
You can use:
if (printResult) {
resolve(printResult)
} else {
reject(console.log('Error'))
}
You can catch exceptions and return them as rejected Promises
function asyncFunc() {
try {
doSomethingSync();
return doSomethingAsync()
.then(result => {
ยทยทยท
});
} catch (err) {
return Promise.reject(err);
}
}
Always check for err if there is any err return a promise (example below)
// Return new promise
return new Promise(function(resolve, reject) {
// Do async job
request.get(options, function(err, resp, body) {
if (err) {
reject(err);
} else {
resolve(JSON.parse(body));
}
})
})

Problems with promises in JavaScript

The last line of code doesn't work and I don't know how to fix it. I understand that second "then" has to return resolve() but how can I realize it?
let getNumber = new Promise((resolve) => {
//API
EthereumNote.getAmountOfMyNotes(function(error, result) {
if (!error) {
let AmountOfMyNotes = Number(result)
resolve(AmountOfMyNotes)
console.log(result)
} else
console.error(error)
})
}).then(result => {
return new Promise((resolve) => {
for (let i = 0, p = Promise.resolve(); i < result; i++) {
p = p.then(_ => new Promise(resolve => {
//API
EthereumNote.getMyNote(i, function(error, result) {
if (!error) {
let text = String(result[0])
let noteID = Number(result[1])
console.log(text)
console.log(noteID)
resolve()
} else
console.error(error)
})
}));
}
})
}).then(() => console.log('Hi!')) // this one doesn't work
Avoid the Promise constructor antipattern! It's ok to make a new Promise to wrap EthereumNote.getMyNote, it's not ok to wrap the loop. You never resolve() that outer promise.
Instead, just return the promise chain you created in p:
let getNumber = new Promise((resolve) => {
//API
EthereumNote.getAmountOfMyNotes(function(error, result) {
if (error) reject(error);
else resolve(Number(result));
})
}).then(amountOfMyNotes => {
console.log(amountOfMyNotes);
var p = Promise.resolve();
for (let i = 0; i < amountOfMyNotes; i++) {
p = p.then(_ => new Promise((resolve, reject) => {
//API
EthereumNote.getMyNote(i, function(error, result) {
if (error) reject(error);
else resolve(result);
});
})).then(result => {
let text = String(result[0])
let noteID = Number(result[1])
console.log(text)
console.log(noteID))
});
}
return p;
}).then(() => {
console.log('Hi!'); // this one now works
}, err => {
console.error(err);
});

Passing an error from one async function to another

I have a convoluted system, which totally works on async/await. What I want is to handle multiple types of errors from an async function in one and only try/catch block. Which means that I call this function from another async function.
But the concept of handling exceptions in a parent async function seems to fail. In the below example what I get - is just a warning about unhandled promise rejection, and the catch block in the parent won't ever get an error. I've tried this also with simply throwing and error, but unsuccessfully either.
const die = (word) => new Promise((resolve, reject) => reject(word));
const live = () => new Promise((resolve, reject) => resolve(true));
const daughterAsync = async () => {
await live();
try {
await die('bye');
} catch (err) {
return Promise.reject(err);
}
try {
await die('have a beatiful time');
} catch (err) {
return Promise.reject(err);
}
await live();
};
const parentAsync = async () => {
try {
daughterAsync();
} catch(err) {
console.log('error catched'); // never happens
console.log(err);
}
};
parentAsync();
I have a feeling that I don't get something about async functions to perform such a stunt
Your daughterAsync(); line only starts the promise running, but it doesn't save the reference to it or wait for it to resolve. You need to await the promise returned by daughterAsync inside of parentAsync's try block in order to catch errors in daughterAsync:
const die = (word) => new Promise((resolve, reject) => reject(word));
const live = () => new Promise((resolve, reject) => resolve(true));
const daughterAsync = async () => {
await live();
try {
await die('bye');
} catch (err) {
return Promise.reject(err);
}
try {
await die('have a beatiful time');
} catch (err) {
return Promise.reject(err);
}
await live();
};
const parentAsync = async () => {
try {
await daughterAsync();
} catch(err) {
console.log('error catched');
console.log(err);
}
};
parentAsync();

Categories

Resources