Switz
Switz

Reputation: 473

Undefined value returned - Javascript

I am receiving a value from a function to pass to a method in a class. When I pass the value returned from the function in web.js, it returns undefined in my shopifyStore class. What could be the reason and how I could solve this ?

PS: Beginner with javascript

web.js

window.shopify.findName({}, function(items) {  
   var shopify = items;

   console.log(items); //this returns the value 
   pushValue(items); 
});

export function pushValue(items) { return items; }

component

import * as shopifyHelper from '/web.js';

class shopifyStore extends HTMLElement {
   constructor() {
      super();
   }

   getItemCount() {
      console.log(shopifyHelper.pushValue()) // this returns undefined
   }
}

Upvotes: 1

Views: 156

Answers (1)

Maksym Bezruchko
Maksym Bezruchko

Reputation: 1258

You should promisify the callback of window.shopify.findName method. Rework your pushValue function:

export function pushValue(items) {
   return new Promise((resolve, reject) => {
      window.shopify.findName({}, items => resolve(items));
   })
}

and call it like this:

async getItemCount() {
   console.log(await shopifyHelper.pushValue());
}

or:

getItemCount() {
   shopifyHelper.pushValue().then(items => console.log(items));
}

Here you can read more about async functions. And here you can read more about promises.

Upvotes: 2

Related Questions