Retrieving information from a Promise

Currently, I am utilizing Tabletop.js to extract data from my Google Spreadsheet. Within the function, I have initiated a Promise. However, I am facing difficulty extracting the Array data out of the function.

The code snippet is as follows:

function getData() {

  return new Promise((resolve) => {
    Tabletop.init({key: publicSpreadsheetUrl, callback: showInfo, simpleSheet: true})
    resolve('Done');
  })
}

let arrayWithData = [];

function showInfo (data, tabletop) {
  console.log('showInfo active');
  arrayWithData.push(...data);
  return new Promise(resolve => {
    console.log(arrayWithData, 'data is here')
    resolve(arrayWithData) // This doesn't work yet
  })
}
 showInfo().then(data => {
   console.log(data, 'data from the Promise')
 }) // This doesn't work

My intention is to utilize this Array later on in React components.

Edit By using Keith's snippet, I managed to make my code functional and also incorporated a reject handler within my Promise of getData() sourced from the MDN site.

Promise.reject(new Error('fail')).then(function() {
  // not called
}, function(error) {
   console.log(error); // Stacktrace
});

The only hurdle now is comprehending the error triggered by my Promise.reject. It displays the following error:

Error: fail
at eval (eval at hmrApply (base.eaab6c8c.js:297), <anonymous>:37:20)
at new Promise (<anonymous>)
at getData (eval at hmrApply (base.eaab6c8c.js:297), <anonymous>:30:10)
at Object.eval (eval at hmrApply (base.eaab6c8c.js:297), <anonymous>:63:1)
at newRequire (script.726c79f3.js:48)
at hmrAccept (base.eaab6c8c.js:328)
at base.eaab6c8c.js:214
at Array.forEach (<anonymous>)
at WebSocket.ws.onmessage (base.eaab6c8c.js:212)

Answer №1

It looks like there are a few issues that need to be addressed in your code.

Firstly, the line showInfo().then should actually be getData().then(.

The next issue lies within your getData function. As mentioned by @ChrisG, you are currently resolving a promise instantly. Here is a corrected version of the function:

function getData() {
  return new Promise((resolve) => {
    Tabletop.init({key: publicSpreadsheetUrl, 
      callback: function (data, tabletop) { resolve(showInfo(data, tabletop)); },
      simpleSheet: true})
  })
}

Additionally, it seems like your showInfo function does not contain any async operations, so it can be simplified as follows:

function showInfo (data, tabletop) {
  console.log('showInfo active');
  arrayWithData.push(...data);
  console.log(arrayWithData, 'data is here')
  return arrayWithData;
}

Lastly, error checking is missing from your code. It's common practice to include some form of error handling mechanism in callbacks, and you may also want to consider adding a reject handler.

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

Issue detected: The validation form is encountering errors due to a blank textarea when utilizing jQuery validate and AJAX for

I am currently working on a spring project that involves registering comments on a specific system design. The page layout for this task is as follows: <form id="formularioCadastroComentario" role="form" method="POST" class="form-horizontal"> &l ...

What is the best way to incorporate a generated ID into the datepicker() function whenever a button is clicked?

I'm looking to dynamically generate a row of input fields with unique IDs every time the "add another flight" button is clicked, similar to the functionality seen on destina.us. Additionally, I need to incorporate these generated IDs into the jQuery U ...

Methods for applying responsive design to react modals in React.js

I am looking to make my modal responsive across different media types. In my React JS project, I have implemented custom styles using the following code: import Modal from 'react-modal'; const customStyles = { content : { top ...

Unexpected updates occurring in custom Google Sheet functions

Currently, I am utilizing a personalized function to retrieve price data for EVE Online. However, I am encountering an issue where the function is updating every 10-20 minutes, leading to a depletion of my daily URL Fetches quota. The primary function can ...

Creating test cases in Dalek.js using functions

I've recently started using Dalek.js for testing and have found it to be quite beneficial. I am interested in taking some tests from one of my files and transferring them into a separate file named "common_tests.js" so that I can reuse them in other l ...

Customizing order and limit features in AngularJS

I have a collection of items that I need to organize into separate lists based on priority levels. items = [ {'type': 2, 'priority': 1, 'name': 'one'}, {'type': 1, 'priority': 2, 'na ...

Display a photo transitioning from black and white to color in a loading fashion, moving from left to right

Is there a way to enhance the clarity of the question's title? I have an interesting effect where text starts off in grey color and then transitions to black using keyframes in CSS with the animate property. I'm curious about how I can achieve ...

Interacting with a card in vuejs won't trigger any action

Is there a way to make an overlay disappear when clicking anywhere on the screen except for a specific card positioned on top of it? The current setup makes the overlay disappear even when the card is clicked. How can this behavior be corrected? <div ...

Amchart 5: Tracking Cursor Movement on the X Axis

I am a beginner with amCharts5 and I am in need of assistance to retrieve the actual X value of the cursor on my chart (where the X axis represents dates). I have come across helpful examples for amCharts 4, but nothing seems to work for amCharts 5. Is thi ...

What could be causing the if/else block in my Redux Toolkit reducer to malfunction?

I'm currently working on a shopping cart feature where I need to increase the quantity of an item if it's already in the cart. If the same item with different sizes is added, they should be displayed separately. I've successfully implemented ...

Discovering the unique identifier of an item in Node.js is simple with these steps

I have a delete API which requires the item's unique ID to be passed in for deletion. How can I capture the ID of the item being deleted and send it to the API? Here is the API: app.post("/delete_product", function (req, res) { var data = { ...

How can I replace specific text with HTML code in a webpage?

In my application, users have the ability to write comments that may contain HTML code. However, this code is escaped before being displayed: <div class="card-body"> <p class="card-text"> &lt;h1&gt;HOLA&lt;/h1&gt; Cita:#2&am ...

Storing JSON values dynamically

On a PHP webpage, I am sending values using JSON. $result = mysql_query("SELECT * FROM user_info"); $i=1; while($row = mysql_fetch_array($result, MYSQL_NUM)) { if(is_array($row) && count($row)>0) { $res[&a ...

Is it possible to selectively process assets based on their type using Gulp and Useref?

Is it possible to selectively process css and js assets using gulp-useref based on the build type specified in the html tags? <!-- build:<type>(alternate search path) <path> --> ... HTML Markup, list of script / link tags. <!-- endbui ...

Refining a JavaScript array of objects based on account category

Currently, I am facing an issue with filtering a JavaScript array that contains objects with boolean properties based on the user's account type. The goal is to filter out the items that do not apply to the specific account type. I have implemented a ...

What could be preventing the onclick event from functioning properly in JavaScript?

After creating a basic JavaScript code to practice Event handling, I encountered an issue where the function hello() does not execute when clicking on the "Click" button. What could be causing this problem? html file: <!DOCTYPE html> <html> ...

What is the correct way to pass parameters when using the setState() function in React hooks?

I am working on a project where I have a list of country names. When a user clicks on one of the countries, I want to update the state with the name of the newly selected country. This state change will then trigger other changes in a useEffect(). The stat ...

Identifying Master Page Controls Post-Rendering

Within my asp.net projects, I have noticed a discrepancy in the control id on the master page's Contentplaceholder1. On my local server, the id appears as "ctl00_Contentplaceholder1_control" after rendering. However, when the application is deployed t ...

Removing the trailing end gutter on each Row in Ant DesignLearn how to eliminate the trailing end

Using antd's Row and Col components to build a responsive grid has presented an issue. Whenever a column moves to a new line because of a breakpoint, there is noticeable white space (likely due to gutters) at the end of the previous line as shown belo ...

Optimal strategies for designing navigation bars on contemporary websites

Struggling to find a solid answer for this dilemma. I have multiple html pages and a single navigation bar that I want to include on all pages for consistency. The idea of duplicating the html code for the navigation bar goes against everything I've l ...