0

I am new to the react.js and javascript world.

I have a promise object called articles, and I want to export default the variable post inside (or outside) the then block.

Approach 1:

articles.then((response) => {

  let posts = response.map(...);

}, (error) => {

  console.log(error);

});

export default posts;  // undefined;

Approach 2:

let posts;
articles.then((response) => {

  posts = response.map(...);

}, (error) => {

  console.log(error);

});

export default posts;  // undefined;

Approach 3:


articles.then((response) => {

  export let posts = response.map(...); // Parsing error: 'import' and 'export' may only appear at the top level

}, (error) => {

  console.log(error);

});


Any suggestions?

xc2333
  • 99
  • 3
  • 10
  • can you tell me what is article ? – heisenberg Mar 13 '20 at 05:47
  • Please read a little bit about concurrency and you will understand why it doesn't make sense to try to export this. The reason #1 doesn't work is because it is locally scoped, #2 doesn't work because the export executes before the Promise does and the default value gets exported which is ```undefined```. #3 .. well so many things wrong with that. You should wrap this inside a function and export the function which will return a Promise, whoever is using the function can later resolve the promise as they wish – sinanspd Mar 13 '20 at 15:29
  • You can just export the promise chain instead. – holi-java Mar 13 '20 at 15:45

0 Answers0