I have written a util class, which is a wrapper around promise based vendor library. My application will call this class (within App & Actions) to perform certain operations.
I am currently dealing with a scenario where my code needs to know the return value of promise within the Util class before proceeding to the next step. How can I do that?
The following is the tree structure of my code:
├── index.html
├── package-lock.json
├── package.json
├── scripts
│ ├── vendor_script.min.js
├── src
│ ├── actions
│ │ └── index.js
│ ├── common
│ │ └── js
│ │ └── WrapperAroundVendorScript_Utils.js
│ ├── components
│ │ └── app.js
│ ├── index.js
│ └── reducers
│ └── index.js
├── style
│ └── style.css
├── webpack.config.js
├── yarn-error.log
└── yarn.lock
Here, vendor_script.min.js is a vendor supplied JS library that uses JS promises to perform various actions. I have written a util class (WrapperAroundVendorScript_Utils.js) to abstract out the implementation details of vendor library.
WrapperAroundVendorScript_Utils.js
let instance = null;
class VendorUtils {
constructor (){
const config = {
some: value,
}
this._vendor = typeof window !== 'undefined' && window.vendor ? window.vendor : require([PATH]);
this._vendor.config = config;
};
static getInstance() {
if(typeof instance == "undefined" || !instance){
instance = new VendorUtils();
}
return instance;
}
doSomething(param1, param2) {
this._vendor.domSomething(param1 + param2);
.then(retVal => {
return {retVal};
});
};
doSomethingElse(param1, param2) {
this._vendor.domSomethingElse(param1 + param2);
.then(retVal => {
return {retVal};
});
};
}
module.exports.VendorUtils = VendorUtils;
app.js
import React, { Component } from 'react';
import {VendorUtils} from '../common/js/VendorUtils';
export default class App extends Component {
clicked(){
let utilsInstance = VendorUtils.getInstance();
let x = utilsInstance.doSomething('a','b');
let y = utilsInstance.doSomethingElse(x,'a');
// call action with values received in previous steps
}
render() {
return (
<div>
<button type='button' onClick={this.clicked}>Click Me!</button>
<button type='button' onClick={this.clicked}>Click Me!</button>
<button type='button' onClick={this.clicked}>Click Me!</button>
</div>
);
}
}
PS: I need such synchronous behavior because there are multiple child/nested/sub components within the class that will be calling such common functions.
.thennot working for you?.thenwould create a promise that would evaluate whenever it gets to execute but by that time the calling function has already moved on to the next line of code. So, value of x would be undefined..thenblock. you could use async / await but thats just promises and generators behind the scene.thencallback (or after anawait)