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.
console.log(value)will happen before the variable is storied. That's the nature of async code.