JavaScript Promise.then()
, how it works and what it returns?
This video covers what is then
method of a Promise
, when to use it and what values it can return.
Code
let p = Promise.resolve('hey bonsaii')p.then(data => console.log(data))p.then(data => data.length)
Full Transcript
00:00 Hi there. Welcome to the JavaScript Series and I'm Deeksha Sharma from bonsaiilabs. To do, we will write some code to see what Promise.then() do and what can it return. In our previous video, we already learned how to create a JavaScript Promise using these two approaches. We will use Promise.resolve() to create a new Promise and call .then() method to get the value. Let's say we have a variable p that holds the resolved Promise from calling Promise.resolve() with value hey bonsaii. So we can call it p.then() to get the value from this Promise. Now then() method takes a function as argument and since p is a fulfilled Promise, we know there would be some data that we can grab inside here. Inside this function, we log its value. Calling then() returns a new Promise. Now, this newly returned Promise will either result to a value if you return something or result to an undefined value if you did not return anything.
01:03 In this case, I just logged the data on the console, so the resulting Promise resolved to an undefined value. Let's try to return for example the length of the data. We call then() and return data.length. Now, in this case, you can see the newly returned Promise is resolved to a value of 11 which is the length of the data string. This is a very common confusion when using JavaScript Promises, and I hope you understand now how then() method works. It will either resolve to a valid value that we returned or will result to an undefined value if we do not return anything. Thanks for watching this video. If you would like to take your JavaScript knowledge to the next level and want to know and understand how browsers execute JavaScript and the role of event loop, check out our new course, which is live. I've added the link in the description below and friends, keep learning and share your knowledge. I'll see you in the next video.