【发布时间】: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