【问题标题】:Get data from a Promise从 Promise 中获取数据
【发布时间】:2018-09-24 11:38:40
【问题描述】:

我正在使用 Tabletop.js 从我的 Google 电子表格中获取数据。在函数中,我调用了一个 Promise。唯一的问题是我无法从函数中获取数据(这是一个数组)。

我有以下代码:

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

我想稍后在 React 块中使用数组

编辑 通过 Keith 的 sn-p,我的代码可以正常工作,并且还从 MDN site 添加了一个 reject 处理程序(在我的 getData() 的 Promise 中)。

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

唯一的问题是,我不明白我从Promise.reject 得到的错误。它返回以下错误:

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)

【问题讨论】:

  • 为什么要创建立即解析的 Promise?您实际上想在这里做什么?您也没有在 showInfo() 调用中传递任何内容,尽管函数似乎期望 data, tabletop
  • 有了 Promise,我正在尝试传递数据(即 arrayWithData),这样我就可以在其他地方使用它,就像在其他函数中一样
  • 你根本不需要 Promise。

标签: javascript es6-promise tabletop.js


【解决方案1】:

你似乎有几个问题..

首先,你有showInfo().then,我很确定你打算这样做 -> getData().then(

您的下一个问题是您的 getData 函数。就像@ChrisG 说的你刚刚在这里立即解决了一个承诺,下面更有可能是你的意思。

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

最后你的 showInfo 没有做任何事情 async 所以它可以被简化为 ->

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

最后一件事,这里没有错误检查,通常回调有一些方法可以通知你错误情况,那么你也可以添加 reject 处理程序。

【讨论】:

  • 我已经使用拒绝处理程序更新了我的代码,它返回一个错误,请参阅主帖。
  • 您可能不得不跳过错误检查,因为快速查看桌面,没有。例如。来源确实 -> } catch (e) { console.error(e); } 这不是很好:(,您可能想联系作者并要求实施错误处理。
猜你喜欢
  • 1970-01-01
  • 2013-10-29
  • 1970-01-01
  • 1970-01-01
  • 2019-03-14
  • 2016-11-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多