2

Fetching an array of users with jsonplaseholder. This array must be exported to another file and there already get what you need from the array (the name property of each of the users). I encounter the fact that the .map () method is not a function

get data:

const fetch = require("node-fetch");

let getMain = new Promise(async function (resolve, reject) {
    let response = await fetch('https://jsonplaceholder.typicode.com/users');
    resolve(response.json());
    reject();
});

getMain.then(mainData => {
    let dataLength = mainData.map(item => item.name.length);
    //console.log(dataLength, mainData);
    return Promise.resolve(dataLength)
})

    .catch(function (err) {
        console.log(err)
    });
//console.log(getMain);
function optionForPie(array) {
    return  array.map(item => item.name.length);
}

export let dataLength = optionForPie(getMain);
    console.log(dataLength);

error:

export let dataLength = optionForPie(getMain);
^^^^^^

SyntaxError: Unexpected token 'export'
?[90m    at Module._compile (internal/modules/cjs/loader.js:895:18)?[39m
?[90m    at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)?[39m
?[90m    at Module.load (internal/modules/cjs/loader.js:815:32)?[39m
?[90m    at Function.Module._load (internal/modules/cjs/loader.js:727:14)?[39m
?[90m    at Function.Module.runMain (internal/modules/cjs/loader.js:1047:10)?[39m
?[90m    at internal/main/run_main_module.js:17:11?[39m
d2207
  • 79
  • 1
  • 8
  • [Never pass an `async function` as the executor to `new Promise`](https://stackoverflow.com/q/43036229/1048572)! – Bergi Jun 11 '20 at 21:05
  • Apart from the issue that you're not using ES6 modules when loading the module, `getMain` is a promise not an array that you can `.map()` over. You *cannot* export an array, it won't be loaded yet. – Bergi Jun 11 '20 at 21:07
  • Can i do export inside `getMain().then()` ? – d2207 Jun 12 '20 at 15:44
  • No. The best thing you can do is to export a promise. – Bergi Jun 12 '20 at 16:16

1 Answers1

0

In order to use ES6 Module syntax, you have to install babel npm package to transpile your ES6 to a commonjs target.

If you don't install babel, you have to use module.exports.