console.log within myFunction() correctly shows its output. However when the function is called from another function, it’s showing String{”} from console.log.
I’m pretty new to javascript. Any advice would be appreciated.
export default class ShippingEstimator {
constructor($element, shippingErrorMessages) {
...
this.initFormValidation();
}
initFormValidation() {
...
$('.shipping-estimate-submit', this.$element).on('click', event => {
if (this.shippingValidator.areAll('valid')) {
console.log(this.myFunction()); // this outputs String {''}
return;
}
});
}
myFunction() {
var str = new String("");
utils.api.cart.getCart({}, (err, response) => {
for (let i = 0; i < response.lineItems.physicalItems.length; i++) {
str = str + '{' + response.lineItems.physicalItems[i].sku + '}|{' + response.lineItems.physicalItems[i].quantity + '}';
}
console.log(str); //this outputs correct data
});
return str;
}
}
I tried using string primitive instead of string object. Again, console.log within myFunction() shows correct output while console.log of its return value from a sibling function shows up as undefined.
3
Answers
You are getting a string output because the function
myFunction
returnsstr
and according to your definition,str = new String("");
You using api request, and work with network its async thing.
So, your request callback calls after you returns string, you need use promises, here can help async/await.
Look at this part here in your code:
What’s happening here is that
utils.api.cart.getCart()
has a callback function. That’s the(err, response) => {
part.That callback function only executes once whenever
getCart
is done.Your code is currently executing
getCart
which takes a little while, but the code is immediately returningstr
which is empty.getCart
isn’t done yet.What you need here is some async/await code, i.e. promises. Sounds like you may be new to javascript, but don’t worry promises aren’t too hard to wrap your head around.
Start out by reading this: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Promises.
Then follow up with looking at the MDN pages for
async
andawait
.