Tapas Adhikary
Educator @tapaScript | Founder CreoWis & ReactPlay - Writer - YouTuber - Open Source
Hello friends π, we are reaching the end of the series, Demystifying JavaScript Promises - A New Way to Learn. So far, we have learned a lot about JavaScript asynchronous programming and promises. If you are new to the series, please check out the p...
blog.greenroots.info8 min read
This is a superb topic which very few people talk about! You made this so easy to understand!
Amazing article! π Thank you so much for sharing this with us βΊοΈ
I think you are the king of JS promises π!
Great article Tapas. Just saw one typo.
.ctach()
You can search and correct.
Thanks,
Tadit
Really Nice article !!
I will take this opportunity to clear my doubts. I code as per below.
const request = require('request');
const test = userData => {
console.log('test::parameters', userData);
if (userData && userData.request === true) {
const option = {
method: 'POST',
url: 'jsonplaceholder.typicode.com/posts&,
headers: {
'Content-type': 'application/json; charset=UTF-8'
},
json: true,
proxy: null,
body: {
title: 'foo',
body: 'bar',
userId: 1
}
};
console.log('test::outgoingBody::', option);
return new Promise((resolve, reject) => {
request(option, (error, response) => {
if (error) {
return reject(error);
} else {
if (response && response.body ) {
return resolve();
} else {
return reject(new Error('Error Response'));
}
}
});
});
} else {
return Promise.reject(new Error('Invalid Userdata'));
}
};
//some business logics
test().catch(err=>console.error(err))
//some business logics
//--------------------------
//some business logics
test({request:true}).catch(err=>console.error(err))
//some business logics
Am I doing correctly?
Great article. I'm embarrassed to admit that I've committed all of the mistakes above, despite the number of times I re-read about promises.
Regarding handling errors within promises, do you think it is essential that web apps display error messages in UI? I think just console.log them is not very helpful.
For such things like loops, filters, groups I use alot library - it designed for lazy iterations over arrays, but also supports
Promisehandlers. The first example would look like this:const names = ['saviomartin', 'victoria-lo']; const users = await alot(names) .mapAsync(async name => { let { data: user } = await axios.get(`api.github.com/users${name}`); return user; }) .toArrayAsync({ threads: 4 })