How to implement promise in nodejs? could anyone provide some examples
for implementation of this?
Thanks in advance.
I agree with the comments on the original question. Docs explain very well. You can find more info here (includes sample)
Or look at the example below.
const asyncThingWithPromise = () => {
var promise = new Promise((resolve, reject) => {
try{
// do something async here. Like get data from a server or read a file from disk etc.
var value = 'My Async Data';
resolve(value) // handled by promise's then()
}catch(error){
reject(error) // handled by promise's catch()
}
});
return promise;
}
// usage with then/catch
asyncThingWithPromise()
.then(value => console.log(value))
.catch(error => console.error(error));
// usage with async / await
try{
const value = await asyncThingWithPromise();
console.log(value);
}catch(err){
console.error(err);
}
Related
Hi,
I have this code on my server file:
getName(){
const promise = new Promise((resolve, reject) => {
conn.query("SELECT name FROM members WHERE id=1", (err, res, fields) => {
if (err) reject(err);
resolve(res);
});
});
}
func() async {
try{
const data = await getName();
console.log(data);
} catch(e) {
console.log(e);
}
}
but I get this error: Unexpected token async so I removed async but then I get another error saying: Unexpected token {
What is happening here? I have node latest version: v10.24.1
Thank you.
The definition of your anonymous async function is wrong, try to change it like this example.
(async function() {
// Your code
})();
Also, you didn't return the promise from your getName() function.
getName() {
return new Promise((resolve, reject) => {
// Your code
})
}
More information about functions and async/await.
I think it is better if you use only async await and don't combine it with try and catch. That may give weird result. Try to refactor it only with async await syntax.
async func(){
const data = await getName();
console.log(data);
}
This question already has answers here:
await is only valid in async function
(14 answers)
Closed 2 years ago.
Ubuntu 20
Node 12.18.4
NPM 6.14.6
Sequelize 6.3.5
I followed the official guide and am so confused now.
After successfully configured Sequelize and connected, I tried to run (from official documentation)
await sequelize.authenticate();
It throws SyntaxError: await is only valid in async function.
Under the official get started page https://sequelize.org/master/manual/getting-started.html, it clearly states:
Most of the methods provided by Sequelize are asynchronous and therefore return Promises. They are all Promises , so you can use the Promise API (for example, using then, catch, finally) out of the box.
Of course, using async and await works normally as well.
That means in your function if you have to await you need to declare an async outside function:
async function() {
await sequelize.authenticate();
}
or
const nameYourFunction = async () => {
await sequelize.authenticate();
}
Remember to declare async before await or you can use the promise if you don't want to declare async await
const nameYourFunction = () => {
sequelize
.authenticate()
.then((result) => {
console.log('nameYourFunction -> result', result);
})
.catch((error) => {
console.log('nameYourFunction -> error', error);
});
};
You have to use async function like this
getStateById: async (req, res) => {
^^^^^^
sequelize.sequelize.transaction(async (t1) => {
let state = await sequelize.state.findOne({
where: {
id: req.params.id
}
});
let result = error.OK;
result.data = state;
logger.info(result);
return res.status(200).send(result);
}).catch(function (err) {
logger.error(err);
return res.status(500).send(error.SERVER_ERROR);
});
}
async is necessary when you want to use await in your app it will be only used in async function type
I'm reading data from db with using await so I used Promise but the function seems to return nothing
async function read() {
return new Promise((resolve, reject) => {
const db = new DB();
db
.read()
.then(result => {
resolve(result);
}).catch(() => {
reject('db-error');
});
});
}
(async () => {
const data = await read();
console.log(data); // undefined
})();
How can I make read() return result?
You are making it more complicated than it has to be. If you are already using an API that returns a promise then there is no need to use the promise constructor yourself.
And declaring a function as async is only necessary if you are using await in it to deal with promises.
So either do:
function read() {
const db = new DB();
return db
.read()
.catch(() => {
return 'db-error';
});
}
Or
async function read() {
const db = new DB();
try {
return await db.read();
} catch(error) {
return 'db-error';
}
}
If you are still not getting the value you want then you are not using the database API correctly and you have to read its documentation to figure out how to get back the right data.
The awesome guys who write the MDN Web Docs say that the result of await will be undefined if the promise that is being waited on is rejected: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await#handling_rejected_promises
Check out the following scenario.
This is a simple function that returns a Promise:
function asyncFunc(waitTime) {
return new Promise((resolve, reject) => {
setTimeout(() => {
// say we prefer people who do things in 3 seconds or less
if (waitTime <= 3000) {
resolve('Promise resolved! You\'re fast! :)');
} else {
reject('Promise rejected! You\'re slow! :(');
}
}, waitTime);
});
}
Let's test the function using a method similar to yours:
async function testAsyncFunc(waitTime) {
try {
const result = await asyncFunc(waitTime);
console.log(result);
} catch(error) {
console.error(error.message);
}
}
testAsyncFunc(3000); // Returns `Promise resolved! You're fast! :)`, as expected
testAsyncFunc(3001); // Returns `undefined` instead of `Promise rejected! You're slow! :(`
But since we want the actual rejection error of the asynchronous operation instead of undefined, the solution is to chain catch to the await statement to catch any rejection errors immediately you call the asynchronous function and then throw the error so it can be caught by any catch error handler you may want to use, like so:
async function testAsyncFunc(waitTime) {
try {
const result = await asyncFunc(waitTime)
.catch(error => {
// throw the rejection error so it can be handled by the catch block below
throw new Error(error);
});
// if no errors
console.log(result);
} catch(error) {
console.error(error.message);
}
}
testAsyncFunc(3001); // Returns the expected result: `Promise rejected! You're slow! :(`
I go on with praticing in JS.
This time, I try to do quite the same thing using async / await or promise :
const url = 'https://jsonplaceholder.typicode.com/todos/1';
Async / await version :
async function getData() {
const response = await fetch(url);
const data = await response.json();
return data;
}
const callGetData = async () => {
try {
const data = await getData()
console.log(data);
} catch (error) {
console.log("Something gone wrong")
}
}
Promise version
function getData() {
return new Promise((resolve, reject) => {
fetch(url)
.then(res => res.json())
.then(data => resolve(data))
.catch(error => reject(error));
});
}
const callGetData = () => {
getData()
.then(data => console.log(data))
.catch(error => console.log("Something gone wrong"));
}
and finally :
callGetData();
Both snippets seem to work. It's easier to me to write the async / await version.
Questions :
do I use promise properly in this case ?
is there some possible improvements ?
Thank you for your help.
fectch is also a promise and you are trying to wrap a promise inside a new Promise
more on the Promise version you can simply return it from the function as
getData(url){
return fetch(url)
.then(response => response.json()).then(jsonResponse=>jsonResponse)
.catch(err=>err)
}
now getData returns a promise. we can simply do as :
getData().then(data=>console.log(data))
I'm trying to return from my node server with koa to my angular front end the result of an api call. Here's my controller which require a npm module which provides access to their api. Await should wait for the result and than return, am I wrong? I did something similar in a previous project but I was asking data from a db.
Why it is not working?
const color = require('colourlovers');
exports.getAllColors = async (ctx) => {
ctx.res.body = await color.get('/color/FFFFFF', { format: 'json' }, (err, data) => {
console.log(data);//<---here is logging the data
return data;
});
console.log(ctx.res.body);//<---here is undefined
ctx.status=200;
};
You can not await color.get because it uses callbacks instead of promises (well, you can await it, but it doesn't do what you'd expect). So to use await, you need to build the promise yourself:
ctx.res.body = await new Promise((resolve, reject) => {
color.get('/color/FFFFFF', { format: 'json' }, (err, data) => {
if(err) reject(err);
else resolve(data);
});
});
Now it'll wait for the promise to be resolved or rejected.