0

I'm working on a Dominos Pizza API right now, and everything seems to work when I console.log() it from the main module (bot.js). If I make a function in my testing file (testnearby.js) that tells it to console.log(localStore), it doesn't print anything. Code below. https://i.stack.imgur.com/ovJMD.png

The function defined that is not working (mentioned above) is getLocalStore

Any help would be appreciated. Code:

bot.js (main module):


//START 

// TABLE OF THINGS ADDED TO BASKET ETC.

var store = "";
var localStore = null;


// FIND LOCAL STORE

exports.getLocalStore = function(postcode) {
    // get the local store
    // get the api and find with the postcode provided
    // fetch the api
    fetch('https://www.dominos.co.uk/storefindermap/storesearch?SearchText=' + postcode)
        // json it
        .then(res => res.json())
        // return it
        .then(function(json) {
            // return console.log(json.localStore)
            // makes it a variable so we can return it elsewhere
            localStore = json.localStore
        })
    return localStore
}
// END


testnearby.js

// START

const ukdomino = require("./bot.js")
const postcode = "L129JH"

ukdomino.getLocalStore(postcode).then(localStore => console.log(localStore))

// END
Ross
  • 128
  • 12
  • And the postcode is fake, but it still works when going to the actual API link. (https://www.dominos.co.uk/storefindermap/storesearch?SearchText=L129JH) – Ross Feb 17 '19 at 09:34
  • `return fetch` not `localStore` – baao Feb 17 '19 at 09:34
  • @bambam Doesn't work for me, says ukdomino.getLocalStore(postcode).then is a function. Changed this as well `ukdomino.getLocalStore(postcode).then(fetch => console.log(fetch))` – Ross Feb 17 '19 at 09:37
  • Please show your actual code then. It works like I described in my answer – baao Feb 17 '19 at 09:40

1 Answers1

1

You need to return fetch ...

exports.getLocalStore = function(postcode) {
    // get the local store
    // get the api and find with the postcode provided
    // fetch the api
    return fetch('https://www.dominos.co.uk/storefindermap/storesearch?SearchText=' + postcode)
        // json it
        .then(res => res.json())

}

The time you return localStore in your function, it's still null since it gets returned before fetch sets its value

baao
  • 71,625
  • 17
  • 143
  • 203
  • 1
    Please don't answer duplicates, instead reference the duplicate and flag the question accordingly. This is probably the most common duplicate on SO. – connexo Feb 17 '19 at 09:38
  • @connexo Apologies, I actually saw that article but I didn't understand it. And this solution works as long as I move `return localStore` below `localStore = json.localStore`. Thanks. – Ross Feb 17 '19 at 09:42
  • 1
    You need to completetely delete the second `then`, and everything thereafter, like in the answer! @Ross – baao Feb 17 '19 at 09:52