简体   繁体   中英

Unable to return value from async method

I need to fetch some Network logs from some async javascript methods, so I wrote below script and it returned the expected value when executed on browser console.

var str=null;
async function ensureFooIsSet() {
    return new Promise(function (resolve, reject) {
        waitForFoo(resolve);
    });
}

async function waitForFoo(resolve) {
    HAR.triggerExport().then(harLog => {
        str=harLog;
        resolve();
    });
};
await ensureFooIsSet().then();
str;

Now I have to get value returned by str variable in my java program, for that I have to run the above script using JavaScriptExecutor, for the str to return value in javaScriptExecutor I have to change the last line of code to return str;

Now I am getting error "Uncaught SyntaxError: await is only valid in async function"

The keyword await is supported in the chrome console without wrapping it in an async function, which explains why your code was working in the console.

However, out of the console, the keywork await must always be used within a function marked async .

When you are at the top of your program, you must use then instead of await , or wrap everything into an async function and call it (IIFE pattern - immediately invoked function expression):

(aysnc function() {
    // do work
    const val = await something();
    // do something with val
})();

// OR

something().then(val => { // do something with val });

However, do not mix await and then as this is redundant. Just assign the value returned by your awaited function to a variable:

const val = await something();

Or use then to access it:

something().then(val => { // do something });

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