- Javascript: How to access the return value of a Promise object
- What is a Promise in Javascript
- 1 — .then() chaining
- 2 — Use returned value later in a code
- Get value from promise javascript
- # Access the value of a Promise in JavaScript
- # If the Promise is rejected, catch() is called
- # The .then() method always returns a Promise
- # Access the value of a Promise using async/await
- # Handling rejected promises in async/await
- # Additional Resources
- Get value from promise javascript
- Метод Promise.resolve
- Определение промиса через функцию
- Гибкая настройка функции
Javascript: How to access the return value of a Promise object
It’s has been almost 3 months since my last blog post. There are reasons for that. First, despite all precautions, I got sick with coronavirus (COVID-19) in the second half of June 2020. For two weeks it was total hell. Very bad well-being, I could only lie in bed and hope that it will go away soon. After that, it was a recovery for the next 2-3 weeks. Now I’m finally got back to normal life and even resumed my fitness training. So, coronavirus is no joke. Please, stay safe. Second, there are lots of things happening right now in my home country — Belarus. Belarussians are fighting against dictatorship. Our (ex)-president lost last elections which were held on August 9th, 2020, but he continues to stay in power using brutal police and army forces against peaceful people and to threaten to anybody who disagrees with him. But we keep on fighting and to protest every day. I do take all these events very close to heart and hope to wake up one day in a free, democratic, and prosperous Belarus. Now back to the topic.
What is a Promise in Javascript
One of the most widely used examples of asynchronous operations in Javascript is a Fetch API. The fetch() method returns a Promise.
Assume that we fetch some data from a backend API. For this blog post, I’ll use JSONPlaceholder — a fake REST API. We will fetch a user’s data with the >
fetch("https://jsonplaceholder.typicode.com/users/1")
Let’s see how we can access returned data.
1 — .then() chaining
It is the most simple and the most obvious way.
fetch("https://jsonplaceholder.typicode.com/users/1") //1 .then((response) => response.json()) //2 .then((user) => console.log(user.address); //3 >);
Here we (1) fetch data from the API, (2) transform it into JSON object and then (3) print user’s address value to the console.
2 — Use returned value later in a code
But what if we’d like to use the returned value somewhere later in code?
If we try to do it like this (wrong way!):
const address = fetch("https://jsonplaceholder.typicode.com/users/1") .then((response) => response.json()) .then((user) => return user.address; >); console.log(address);
It’s happening because the Javascript code always executes synchronously, so the console.log() function starts immediately after the fetch() request, not waiting until it is resolved. In the moment when console.log() function starting to run, a Promise that should be returned from a fetch() request is in a pending status.
That said we can access the returned value of a Promise object in another .then() callback:
const address = fetch("https://jsonplaceholder.typicode.com/users/1") .then((response) => response.json()) .then((user) => return user.address; >); const printAddress = () => address.then((a) => console.log(a); >); >; printAddress();
OR using async / await syntax:
const address = fetch("https://jsonplaceholder.typicode.com/users/1") .then((response) => response.json()) .then((user) => return user.address; >); const printAddress = async () => const a = await address; console.log(a); >; printAddress();
Get value from promise javascript
Last updated: Jan 10, 2023
Reading time · 4 min
# Access the value of a Promise in JavaScript
Use the Promise.then() method to access the value of a promise.
The then() method takes a function, which gets passed the resolved value of the promise as a parameter.
Copied!// 👇️ Example promise const p = Promise.resolve('bobbyhadz.com'); p.then(value => console.log(value); // 👉️ "bobbyhadz.com" >).catch(err => console.log(err); >);
We used the Promise.resolve() method to get an example promise.
We called the then() method on the Promise object to resolve the promise.
The function we passed to the then() method gets called with the resolved value as a parameter.
We can access this value in the body of the function.
Notice that we also used the catch() method.
This is because a promise can have 3 states:
- pending — initial state, neither fulfilled nor rejected.
- fulfilled — the operation was successful and the promise is resolved.
- rejected — operation failed.
The function we passed to the then method will get called if the promise is fulfilled and the operation was successful.
# If the Promise is rejected, catch() is called
If the promise is rejected, we can access the reason (error) for the rejection in the catch() method.
Copied!// 👇️ Example rejected promise const p = Promise.reject('Something went wrong'); p.then(value => console.log(value); >).catch(err => console.log(err); // 👉️ "Something went wrong" >);
We used the Promise.reject() method to get a rejected promise.
This time, our catch method was invoked and got passed the reason for the rejection.
# The .then() method always returns a Promise
The value you return from the function passed to the then() method is wrapped in a promise, so you can chain as many calls to the method as necessary.
Copied!const p = Promise.resolve(13); p.then(value => console.log(value); // 👉️ 13 return value + value; >).then(value => console.log(value); // 👉️ 26 return value + value; >);
If you don’t return a value from the callback function, you implicitly return undefined , which gets wrapped in a promise and returned by the then() method.
Alternatively, you can access the value of a promise by using the async/await syntax.
# Access the value of a Promise using async/await
To access the value of a promise using async/await:
- Define an async function.
- Use the await operator to await the promise.
- Assign the result of using the await operator to a variable.
Copied!// 👇️ example promise const p = Promise.resolve('bobbyhadz.com'); async function example() try const value = await p; console.log(value); // 👉️ "Hello World" > catch (err) console.log(err); > > example();
We can use the await operator because we marked the function as async .
The await operator is used to wait for a Promise to be fulfilled or rejected.
An easy way to think about the await operator is that:
- When the await operator is used, our code in the particular function stops on the line where await was used until the Promise is fulfilled or rejected.
This makes our code much easier to read compared to using the then() method.
# Handling rejected promises in async/await
Notice that we wrapped the operation in a try/catch block.
This is because, if the promise gets rejected, we want to be able to access the reason in our catch block.
Copied!// 👇️ Example rejected promise const p = Promise.reject('Something went wrong'); async function example() try const value = await p; console.log(value); > catch (err) console.log(err); // 👉️ "Something went wrong" > > example();
We used the Promise.reject() method to get a rejected promise.
When we tried to await the promise, our catch function was called and passed the reason for the rejection.
There are many use cases where you might want to use the await operator outside of a function.
Copied!// 👇️ Example promise const p = Promise.resolve('bobbyhadz.com'); try const value = await p; console.log(value); // 👉️ "bobbyhadz.com" > catch (err) console.log(err); >
The top-level await syntax is available in Node.js if your Node version is 16.12.0 or more recent.
If you intend to use top-level await in the browser, check out the caniuse table for browser support for top level await.
At the time of writing, the top-level await operator can be enabled for most modern browsers by loading the JavaScript file as a module in your HTML file.
Copied!script type="module" src="index.js"> script>
Notice that we set the type attribute to module .
When using top-level await , it is very important to use a try/catch block because an uncaught exception caused by a rejected promise might stop your application from running.
Copied!// 👇️ Example rejected promise const p = Promise.reject('Something went wrong'); try const value = await p; console.log(value); > catch (err) // 👇️ catch the error here console.log(err); // 👉️ "Something went wrong" >
If a rejection of a promise is not handled, e.g. in a catch block, your server might be in an inconsistent state.
It’s a best practice to use a try/catch block when working with the await operator.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
Get value from promise javascript
Ранее мы рассмотрели, как из функции промиса мы можем передать во вне результат асинхронной операции:
const myPromise = new Promise(function(resolve)< console.log("Выполнение асинхронной операции"); resolve("Привет мир!"); >);
Теперь получим это значение. Для получения результата операции промиса применяется функция then() объекта Promise :
then(onFulfilled, onRejected);
Первый параметр функции — onFulfilled представляет функцию, которая выполняется при успешном завершении промиса и в качестве параметра получает переданные в resolve() данные.
Второй параметр функции — onRejected представляет функцию, которая выполняется при возникновении ошибки и в качестве параметра получает переданные в reject() данные.
Функция then() возвращает также объект Promise .
Так, получим переданные данные:
const myPromise = new Promise(function(resolve)< console.log("Выполнение асинхронной операции"); resolve("Привет мир!"); >); myPromise.then(function(value)< console.log(`Из промиса получены данные: $`); >)
То есть параметр value здесь будет представлять строку «Привет мир!» , которая передается в resolve(«Привет мир!») . В итоге консольный вывод будет выглядеть следующим образом:
Выполнение асинхронной операции Из промиса получены данные: Привет мир!
При этом нам необязательно вообще передавать в resolve() какое-либо значение. Возможно, асинхронная операция просто выполняется и передает во вне никакого результата.
const x = 4; const y = 8; const myPromise = new Promise(function()< console.log("Выполнение асинхронной операции"); const z = x + y; console.log(`Результат операции: $`) >); myPromise.then();
В данном случае функция в промисе вычисляет сумму чисел x и y и выводит результат на консоль.
Метод Promise.resolve
Иногда требуется просто вернуть из промиса некоторое значение. Для этого можно использовать метод Promise.resolve() . В этот метод передается возвращаемое из промиса значение. Метод Promise.resolve() возвращает объект Promise:
const myPromise = Promise.resolve("Привет мир!"); myPromise.then(value => console.log(value)); // Привет мир!
Определение промиса через функцию
Нередко промис определяется через функцию, которая возвращет объект Promise. Например:
function sum(x, y)< return new Promise(function(resolve)< const result = x + y; resolve(result); >) > sum(3, 5).then(function(value)< console.log("Результат операции:", value);>); sum(25, 4).then(function(value)< console.log("Сумма чисел:", value);>);
Здесь функция sum() принимает два числа и возвращает промис, который инкапсулирует операцию сумму этих чисел. После вычисления сумма чисел передается в resolve() , соответственно мы ее затем можем получить через метод then() . Определение промиса через функцию позволяет нам, с одной стороны, при вызове функции передавать разные значения. А с другой стороны, работать с результатом этой функции как с промисом и настроить при каждом конкретном вызове обработку полученного значения.
Результат работы программы:
Результат операции: 8 Сумма чисел: 29
Однако, что если у нас совпадает принцип обработки полученного из асинхронной функции значения?
sum(3, 5).then(function(value)< console.log("Результат операции:", value);>); sum(25, 4).then(function(value)< console.log("Результат операции:", value);>);
В этом случае логика обработки будет повторяться. Но поскольку метод then() также возвращает объект Promise, то мы можем сделать следующим образом:
function sum(x, y)< return new Promise(function(resolve)< const result = x + y; resolve(result); >).then(function(value)< console.log("Результат операции:", value);>); > sum(3, 5); sum(25, 4);
Гибкая настройка функции
А что, если мы хотим, чтобы у программиста был выбор: если он хочет, то может определить свой обработчик, а если нет, то применяется некоторый обработчик по умолчанию. В этом случае мы можем определить функцию обработчика в качестве параметра функции, а если он не передан, то устанавливать обработчик по умолчанию:
function sum(x, y, func)< // если обработчик не установлен, то устанавливаем обработчик по умолчанию if(func===undefined) func = function(value)< console.log("Результат операции:", value);>; return new Promise(function(resolve)< const result = x + y; resolve(result); >).then(func); > sum(3, 5); sum(25, 4, function(value)< console.log("Сумма:", value);>);
Здесь при первом вызове функции sum() ( sum(3, 5) ) будет срабатывать обработчик по умолчанию. Во втором случае обработчик явным образом передается через третий параметр, соответственно он будет задействован sum(25, 4, function(value)< console.log("Сумма:", value);>)