Get data from a Promise

天涯浪子 提交于 2020-01-16 16:24:48

问题


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)

回答1:


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.



来源:https://stackoverflow.com/questions/52478547/get-data-from-a-promise

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!