1

I have an async fuction which successfully retrieves a json object but I can't store this output in an array/variable which I want to use outside the function itself. The problem is not to console log the output but store the output in 'myObject' just like a normal JSON object that you can work with.

    "use strict"
    const fetch = require('node-fetch')


    async function getValue() {

      let response = await fetch('https://api.pro.coinbase.com/products/btc-eur/ticker')

      let value = await response.json()

      return value
    }

    getValue().then(function(value) {myObject = value})

As has been discussed the myObject variable cant be assigned this way. Im still struggling with async and callbacks, even tho I understand how the callback and event loops work! My solution is to save the contents of this web request as a JSON file which is what I wanted to do anyway. In future if I need this data I can extract it globally.

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

async function getValue(callback) {

  let response = await fetch('https://api.pro.coinbase.com/products/btc-eur/ticker')

  let value = await response.json()

  return value
}

getValue().then(result => {
  console.log(result)
  const dataJSON = JSON.stringify(result)
  fs.writeFileSync('coinbase-web.JSON', dataJSON)
})

Now data is safely stored in a JSON file I can now create an object from this file or even better, I should be able to parse this data directly within Excel which is my next step.

1
  • The problem isn't storing the value, it's when you store it. Your console.log(value) will happen before the variable is storied. That's the nature of async code. Commented Apr 22, 2019 at 23:37

3 Answers 3

1

The first error is unrelated to the async response.

You are using the use strict directive, which requires all variables to be declared - but you have not declared myObject when you are trying to assign to it.

Just declare it and then uncomment the first line of your promise handling code, which looks like it should work - and then console log inside your then() event body (otherwise you'll be logging the value before your async process has completed).

See https://www.w3schools.com/js/js_strict.asp

var myObject;
getValue().then(function(value) {
  myObject = value;
  console.log(myObject);
  // you must handle myObject here, not in the synchronous code outside
});

//console.log(myObject); //this will not work because it does not wait for your then function to complete.

If you're still unsure of how to use the result, read this excellent guide: https://javascript.info/async-await

Sign up to request clarification or add additional context in comments.

4 Comments

Ok thanks for your help guys. I will do some more reading and figure it out. I thought it was something simple I overlooked but havn't covered async in my course yet.
@Mamba76 Here's a working example of your code you can play with online: repl.it/repls/AchingLeftInfo
Thanks Steve, that's an interesting tool Im sure will prove useful later. Im out of my depth with the async await functions ATM. The code was suggested in a previous question and it works great but Ill try another method to achieve my goal which is simply to store the contents of this web request as an object in Node .Im familiar with https so maybe will look at this again.
Good luck! I'd strongly recommend spending 30 mins reading about async/await - its really powerful and quite simple to use once you grasp the basic concept :)
0
getValue().then(function(value) {
    console.log(value)
 /* How store completed output as a global object? */});

you need to wait for response and then log

Comments

0

No, sorry. Because the code is asynchronous that is not possible.

You have to either handle it in the then method

getValue().then(value => { 
  console.log("value:", value);
});

or use a Self-Executing Anonymous Function

(async () => {
  console.log("values:", await getValue());
})();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.