Search code examples
es6-promise

how to access a function in a promise


my code in react application

I have I class:

class SampleModuleController{

    getSampleModuleSheet()
    {
       console.log("getSampleModuleSheet");
       return tableSheet;
    }
    retrivePageData(pageNumber,pageLength){
        
        console.log("retrivePageData calledd");
        let pageData= asyncAwaitService.findTablePageTestData(pageNumber,pageLength);
        return pageData;
    }
}

export let sampleModuleController = new SampleModuleController();

SampleModuleController class lazy loaded and its getSampleModuleSheet method can use successfully.

in jsx:

<DataTable getPageData={import('../controllers/sampleModuleContrller').then(({sampleModuleController}) => {return sampleModuleController.retrivePageData;})} />

in js file:

async newPageManager(){
    console.debug("this.props.getPageData------",this.props.getPageData);
    let pageData = await props.getPageData(1,34);
}

out put

enter image description here

so how can I call the fuction inside the promise


Solution

  • in your jsx, it's apparent that the promise returns a method delegate.

    So, this.props.getPageData when resolved with await will result in a method delegate that is itself to be invoked on.

    we'll modify your snippet as followed;

    async newPageManager(){
        console.debug("this.props.getPageData------",this.props.getPageData);
        let getPageData = await props.getPageData; 
        let pageData = getPageData(1,34);
    }
    

    additionally, since props.getPageData is returning a promise, it is thenable.

    so, you could pass the result of that promise into a then function scope -- something like the following

    async newPageManager(){
        console.debug("this.props.getPageData------",this.props.getPageData);
        let getFirstPagePromise = props.getPageData.then((fn) => fn.bind(this, 1, 32)); 
        let getFirstPage = await getFirstPagePromise;
        let pageData = getFirstPage();
    }