"Unlocking the outcome of a promise: step-by-step guide

I'm struggling to extract the string "foo" from my Promise. I'm starting to think that my Promise declaration is incorrect.

const bar = new Promise((res, rej) => res("foo"));
then((result) => {
  return result;
});

Answer №1

Here is the recommended approach:

const variable = new Promise((resolve, reject) => resolve("value"));

variable.then((result) => {
     console.log(result);
    // perform any desired actions with result
}).catch(error=>console.log(error))

The then function gets executed upon successful resolution of the promise. The catch method triggers when the promise is rejected.

Answer №2

const example = new Promise((resolve) => resolve("hello"))
.then((output) => {
  console.log(output)
});

👉 Remember to include a period (.) before the word then -> .then

then is a method of the Promise object, so you must use .then to invoke the method. then cannot be used independently as a global function.


When you write:

new Promise((resolve) => resolve("hello")).then((output) => ...

the then will only execute upon successful resolution of the Promise.

The Promise internally tracks all then methods and triggers them when you call resolve("hello") (in this case), hence the need for .then - to register those callbacks to be executed upon resolution

Answer №3

When you assign the Promise to the variable bar, make sure to use then to retrieve the value like this:

const bar = new Promise((res, rej) => res("foo")).then((result) => {
  console.log(result)
});

It's also important to include a catch statement for error handling.

If you're looking to learn more about Promises, check out this free course on Udacity from Google to improve your understanding.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Combining two arrays using conditions in Lodash

I have two different arrays as shown below: const firstArray = [{name: "1"}, {name: "2"}, {name: "3"}, {name: "4"}, {name: "4"}]; const secondArray = [{name: "1"}, {name: "5"}, {name: &q ...

What could be causing my canvas to not display my sprite?

Currently, I am in the process of learning JavaScript and experimenting with creating games to make the learning experience more enjoyable. However, I am facing an issue while using EaselJS and CreateJS to develop these games as a beginner. I need some as ...

The variable within my function is not being cleared properly despite using a jQuery function

Recently, I encountered an issue with a function that displays a dialog box to ask users if their checks printed correctly. Upon clicking on another check to print, the "checked_id" value remains the same as the previously executed id. Surprisingly, this i ...

Dealing with data manipulation in the realm of javascript

In the following code snippet, I am iterating through multiple URLs and extracting data (title and content) from each of them. My objective is to store this data for later use on another page, and thus it needs to be accessible using its respective title, ...

Leveraging data from various Fetch API calls to access a range of

As a beginner with Fetch API and Promises, I have encountered an issue that I hope someone can help me with. My code involves fetching event data with a token, extracting team ids, and using these ids to fetch more information from another endpoint. Every ...

Enhance the appearance of Ionic popups

Can someone help me with resizing a pop up? I've been struggling to get it right. This is the popup template in question: <ion-view> <ion-content scroll="false" class=""> test </ion-content> < ...

What is the maximum number of data points that can be used in a Scatter plot created

I am currently facing an issue while trying to populate a Scatter plot in JavaScript with decimal values obtained from a MySQL database using PHP. The database contains around 150,000 entries, resulting in 150,000 pairs of decimal inputs for the graph. How ...

Displaying images retrieved from firebase on a React.js application

Currently, I am attempting to retrieve images from Firebase storage and then exhibit them in a React component. As a newcomer to React/Javascript, I find it challenging to grasp the asynchronous nature of React/JS. The issue I'm facing is that althoug ...

Issue: appbridgeError: APP::ERROR::INVALID_CONFIG: shopOrigin is a required field and must be provided

While developing my Shopify App using Koa and Nextjs, I encountered the following error: appbridgeError: APP::ERROR::INVALID_CONFIG: shopOrigin must be provided The behavior of the app is a bit odd as it works fine when accessed for the first time. Howev ...

Executing the executeScript method in Microsoft Edge using Java and WebDriverWould you like a different version?

I'm currently attempting to execute the following code in Microsoft Edge using WebDriver ExpectedCondition<Boolean> jsLoad = driver -> ((JavascriptExecutor) driver).executeScript("return document.readyState").toString().equals(&quo ...

Checking CORS permissions with a pre-flight OPTIONS request

During development, I implement a middleware called cors using the following syntax: app.use(cors({origin: 'http://localhost:8100'})); However, I have noticed that for every route request, two requests are being made as shown in the image below ...

Having issues with 'direction' in React withStyles causing errors

I am experiencing an issue with my React website where I am using the withStyles feature to apply styles to a material-ui Grid element. Specifically, when attempting to use direction: "column" in the style, I encounter the error message provided below. Th ...

Type for the key in array.reduce that is not specific or unique

Given an array of objects, I use the reduce method to transform it into a new format where each key represents a date from the original array. For example, if the array contains objects with dates like {date: '22-02-06-00:55:66', name: 'one& ...

In certain instances, a modal popup may intermittently fail to hide after the page has finished loading, an issue observed

Upon page load, an ajax modal pop-up is displayed and then hidden once the loading process is complete. This functionality is defined within the master page. The issue arises when certain button clicks fail to trigger the window.onload javascript event, as ...

Tips for concealing title when window is resized?

I'm working on a webpage that has a title at the top, but I want to hide it on smaller devices and make it responsive when the window is resized. Currently, I only show the title when the window width (w) is greater than 450 pixels. However, I'm ...

Generate a new entity using a previously imported model with A-Frame

I have successfully imported a house model in .gltf format. I am now trying to extract the floor object from this model and turn it into its own individual a-frame entity for future reference. This is necessary so that I can designate the floor as the coll ...

How can I retrieve the results of an SQLite call in HTML5 without passing them to a separate function?

How can I use SQLite in HTML5 to execute a call like the one below, so that the result is returned immediately rather than passed off to another function? try { mydb.transaction( function(transaction) { transaction.executeSql( &apo ...

What is the best method for importing OrbitControls into my three.js project?

I'm having trouble importing OrbitControls into my project. I included three.js and then attempted to import OrbitControls, but it's not functioning as expected. I added three.js to the HTML body using the following command: script src="https:/ ...

How can TypeScript and MobX work together using Set()?

I'm encountering errors while trying to implement Set() in my Grocery Shopping app using MobX with TypeScript. I have a simple setup with defined types in types.ts: types.ts export type Item = { name: string; instock: number; price: number; }; ...

Utilizing the power of Web SQL Database with a dynamic Javascript loop

I'm currently facing a challenge that I could use some help with... While experimenting with Web SQL Databases, I've encountered an issue when trying to create a loop that functions correctly. Here's the code snippet I'm using: for ...