1

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
   }
}
5
  • Try export default pushValue; And import it as import { pushValue } from './web.js'; Commented Nov 11, 2020 at 9:40
  • @TrishantPahwa, can you explain how different your answer is, please ? Commented Nov 11, 2020 at 9:44
  • I guess the way your are exporting and importing the function is incorrect. Commented Nov 11, 2020 at 9:46
  • @TrishantPahwa returns undefined Commented Nov 11, 2020 at 9:50
  • Might need to see your log. Do you have discord? Commented Nov 11, 2020 at 9:51

1 Answer 1

2

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.

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

3 Comments

That was only a typo:). It actually returns undefined because the value is not ready yet. (callback).
You have any help ? I am just starting with JS
Thanks. you are the best

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.