如何导出承诺结果? [英] How can I export promise result?
问题描述
很抱歉,如果这个问题很愚蠢。
Sorry if this question is stupid.
此代码可以正常使用。并且我只需要在所有promises成功解析后导出数据变量。
This code works correctly. And I just need to export data variable after all promises successfully resolved.
我不能将此代码用于函数和导出变量。因为在这种情况下,此函数将导出一个空数组。
I cannot put this code to function and export variable. Because in this case, this function will export an empty array.
'use strict'
import urls from './urls'
import getData from './get-data'
getData(urls).then((responses) => {
const data = []
const results = responses.map(JSON.parse)
for (let i = 0, max = results.length; i < max; i++) {
// some magic and pushing
}
return data
}).catch(error => console.log(error))
推荐答案
您可以轻松地将其分配给导出的变量,但您应该不这样做 - 赋值是异步发生的,并且可以在导入它的模块中读取变量。
You could easily assign it to an exported variable, but you should not do that - the assignment happens asynchronously, and the variable might be read before that in the modules where it is imported.
所以相反,只需导出promise 1 !
So instead, just export the promise1!
// data.js
import urls from './urls'
import getData from './get-data'
export default getData(urls).then(responses =>
responses.map(JSON.parse).map(magic)
);
// main.js
import dataPromise from './data'
dataPromise.then(data => {
console.log(data);
…
}, console.error);
1:直到建议顶级 await
出现,您可以在导出前等待该值它。
这篇关于如何导出承诺结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!