How can I export promise result?

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.

Leave a Comment