Search code examples
javascriptes6-promisetabletop.js

Get data from a Promise


I'm working with Tabletop.js to get data from my Google Spreadsheet. In the function, I've invoked a Promise. The only problem is I can't get the data(which is an Array) out of the function.

I have the following code:

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

I want to use the Array later on in React blocks

Edit With the snippet of Keith, I've got my code working & also added a reject handler(inside my Promise of getData() ) from the MDN site.

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

The only thing is, that I don't understand the error I get from my Promise.reject. It returns 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)

Solution

  • You seem to have a couple of issues here..

    Firstly, you have showInfo().then, I'm pretty sure you meant to do -> getData().then(

    Your next problem is your getData function,. like @ChrisG said your just resolving a promise instantly here, below is more likely what you meant to do.

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

    Lastly your showInfo is not doing anything async so it can be simplified to ->

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

    One last thing, there is no error checking here, normally callbacks have some way to inform you of an error condition, then you could also add the reject handler.