简体   繁体   中英

Get a value inside a Promise Typescript

One of function inside a typescript class returns a Promise<string> . How do I unwrap/yield the value inside that promise.

functionA(): Promise<string> {
   // api call returns Promise<string>
}

functionB(): string {
   return this.functionA() // how to unwrap the value inside this  promise
}

How do I unwrap/yield the value inside that promise

You can do it with async / await .Don't be fooled into thinking that you just went from async to sync, async await it is just a wrapper around .then .

functionA(): Promise<string> {
   // api call returns Promise<string>
}

async functionB(): Promise<string> {
   const value = await this.functionA() // how to unwrap the value inside this  promise
   return value;
}

Further

Try this

functionB(): string {
   return this.functionA().then(value => ... );
}

My working code snippet(to switch to a window containing url string)::

browser.getAllWindowHandles().then(function (handles) {
                    var length = handles.length;
                    console.log("count of windows::"+length);
                    for (var index=0;index<length;index++) {
                        var newTab = handles[index];
                        browser.switchTo().window(newTab).then(function () {
                            browser.driver.getCurrentUrl().then(value => {
                                console.log("Printing current url::"+value);
                                if(value.includes("limits")) {
                                    console.log("found limits");
                                }
                            })
                        });
                    }
                });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM