0

I have been trying to fix this but it gives me this: ReferenceError: json is not defined

this is my code:

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

function makeAFile(text){
    fetch("http://bin.shortbin.eu:8080/documents", {
        method: "post",
        body: 'hey wassup'
    })
    .then(res => res.json())
    .then(json => console.log(json))
    .catch(err => console.log(err))
    return json
}

console.log(makeAFile('nope'))
OpenSaned
  • 105
  • 1
  • 1
  • 8
  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Evert Feb 13 '21 at 09:30

4 Answers4

0

You seem to be confused with how to return data from an async call. You do that using callbacks like this:

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

function makeAFile(text){
  return fetch("http://bin.shortbin.eu:8080/documents", {
    method: "post",
    body: text
  })
  .then(res => res.json())
  .catch(err => { console.error(err) })
}

makeAFile('nope').then((result) => console.log(result));

You can read more about it here;

EDIT: Provide a solution using async/await

async function makeAFile (text) {
  try { 
    const res = await fetch("http://bin.shortbin.eu:8080/documents", {
      method: "post",
      body: text
    })
    return res.json();
  } catch (err) {
    console.error(err);
  }
}

// Define an anonymous async function to allow await statements inside
(async () => {
  // this "await" here is important
  const result = await makeAFile('nope');
  console.log(result);
  // now result is store inside of "result"
})();
comonadd
  • 1,822
  • 1
  • 13
  • 23
  • there is no need to create a Promise because `fetch` is already an async function. – Anatoly Feb 13 '21 at 09:16
  • @Anatoly You're right. I've removed new Promise allocation – comonadd Feb 13 '21 at 09:19
  • but what if i want to store the var – OpenSaned Feb 13 '21 at 09:38
  • @BRUH Do what you want to do with the result inside of the callback. You can store the result inside of a global variable but beware that the code after calling `makeAFile` will run right away and it won't wait for the callback to run so it won't have access to the updated values. – comonadd Feb 13 '21 at 09:54
  • @BRUH You can use the new `async/await` syntax to get rid of callbacks and call async functions in a linear style. You can read about it [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) – comonadd Feb 13 '21 at 09:57
  • @BRUH Updated the answer with `async/await` code – comonadd Feb 13 '21 at 10:01
0

You don't have access to json outside then callback. Just make your function async, that way you will have an access to it and outer context code can wait till your function will be resolved or rejected:

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

async function makeAFile(text){
    const res = await fetch("http://bin.shortbin.eu:8080/documents", {
        method: "post",
        body: 'hey wassup'
    })
    const json = res.json()
    console.log(json)
    return json
}

and call it like:

try {
  const result = await makeAFile('nope')
  console.log(result)
} catch(err) {
  console.log(err)
}

or

const result = makeAFile('nope').then(result => {
  console.log(result)
})
.catch(err => {
  console.log(err)
});
Anatoly
  • 20,799
  • 3
  • 28
  • 42
0

You need to understand, how async call works.

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

function makeAFile(text){
    fetch("http://bin.shortbin.eu:8080/documents", { // this is async call
        method: "post",                              // might give result later in time
        body: 'hey wassup'
    })
    .then(res => res.json())
    .then(json => console.log(json))
    .catch(err => console.log(err))
    return json                     // JSON is not defined and will be return just after 'Fetch' is called which is 'undefined'

console.log(makeAFile('nope'));

To make your code sync, you should use async await like this:

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

async function makeAFile(text){
    let res = await fetch("http://bin.shortbin.eu:8080/documents", { // await helps you to wait here to make your code sync
        method: "post",                              
        body: 'hey wassup'
    })
     const json = res.json()
     
    return json ;                                
}

try {
const response = await makeAFile('nope')); //use try catch to catch error
console.log(response);
}
catch (error) {
console.log(`Error ${error}`);
} 

Apoorva Chikara
  • 8,277
  • 3
  • 20
  • 35
-1
const fetch = require('node-fetch');

function makeAFile(text){
    jsonOut = ''
    fetch("http://bin.shortbin.eu:8080/documents", {
        method: "post",
        body: 'hey wassup'
    })
    .then(res => res.json())
    .then(json => jsonOut = json)
    .catch(err => console.log(err))
    return jsonOut
}

console.log(makeAFile('nope'))

you cannot access value inside a promise. Just check this code

Alex
  • 36
  • 7