返回未定义的值-Javascript
我从一个函数接收一个值,传递给类中的一个方法。当我在web.js中传递函数返回的值时,它在我的shopifyStore类中返回undefined。原因是什么?我如何解决这个问题 PS:javascript初学者 web.js返回未定义的值-Javascript,javascript,Javascript,我从一个函数接收一个值,传递给类中的一个方法。当我在web.js中传递函数返回的值时,它在我的shopifyStore类中返回undefined。原因是什么?我如何解决这个问题 PS:javascript初学者 web.js window.shopify.findName({}, function(items) { var shopify = items; console.log(items); //this returns the value pushValue(it
window.shopify.findName({}, function(items) {
var shopify = items;
console.log(items); //this returns the value
pushValue(items);
});
export function pushValue(items) { return items; }
组件
import * as shopifyHelper from '/web.js';
class shopifyStore extends HTMLElement {
constructor() {
super();
}
getItemCount() {
console.log(shopifyHelper.pushValue()) // this returns undefined
}
}
您应该提示调用
window.shopify.findName
方法。重新编写pushValue
函数:
export function pushValue(items) {
return new Promise((resolve, reject) => {
window.shopify.findName({}, items => resolve(items));
})
}
这样称呼它:
async getItemCount() {
console.log(await shopifyHelper.pushValue());
}
或:
您可以阅读有关异步函数的更多信息。
您还可以阅读有关承诺的更多信息。尝试导出默认值并将其作为
import{pushValue}从'/web.js'导入代码>@TrishantPahwa,你能解释一下你的答案有多不同吗?我猜你导出和导入函数的方式是不正确的。@TrishantPahwa返回Undedminight需要查看你的日志。你有意见分歧吗?那只是一个打字错误:)。它实际上返回undefined,因为该值尚未准备就绪。(回电话)有什么帮助吗?我刚开始说谢谢。你是最棒的
getItemCount() {
shopifyHelper.pushValue().then(items => console.log(items));
}