从承诺中获取数据 [英] Get data from a Promise
问题描述
我正在使用 Tabletop.js 从我的Google电子表格中获取数据。在函数中,我调用了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.
我有以下代码:
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块中使用Array
I want to use the Array later on in React blocks
编辑
有了Keith的代码段,我的代码可以正常工作了。还从
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
});
唯一的是,我不理解从<$ c $中得到的错误c> Promise.reject 。它返回以下错误:
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)
推荐答案
您
首先,您有 showInfo()。然后
,我是我很确定你打算这么做-> getData()。then(
Firstly, you have showInfo().then
, I'm pretty sure you meant to do -> getData().then(
下一个问题是您的getData函数,就像@ChrisG所说的那样,您刚刚在这里立即兑现诺言,下面更可能是您的意思。
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})
})
}
最后,您的showInfo没有执行任何操作异步
,因此可以简化为->
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.
这篇关于从承诺中获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!