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.
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: Until the proposed top-level await
comes along and you can just wait for the value before exporting it.
EDIT 2021
Since node now support top-level-await
the solutions is extra basic
export await new Promise()
import foo from './foo.js' // the import wait for the promise to be resolved
console.log(foo)
Nowadays u do
const wait = ms => new Promise(resolve => setTimeout(resolve, ms))
async function foo() {
console.log('called')
await wait(1000)
return 'hi'
}
export default foo()
import foo from './foo'
void (async function() {
console.log(foo)
console.log(await foo)
console.log(await foo)
})()
> called
> Promise { <pending> }
> hi
> hi
It's usefull to fetch datas at start
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With