How can I export promise result?

前端 未结 4 1113
南笙
南笙 2021-01-07 23:12

Sorry if this question is stupid.

This code works correctly. And I just need to export data variable after all promises successfully resolved.

I cannot put t

4条回答
  •  爱一瞬间的悲伤
    2021-01-07 23:57

    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.

提交回复
热议问题