Home > Software engineering >  JavaScript How to output the value of result1 and result2
JavaScript How to output the value of result1 and result2

Time:05-11

The script below outputs only the value of variable "result2"

How to output the value of "result1" and "result2" without using console.log, cuz i will put this script in the cefSharp framework of C#, cefSharp does not output data that is in "console.log"

enter image description here

var result;
var result2;
const myPromise = new Promise(
function(resolve)
{
    var a1 = 2   2;
    resolve(a1);
}
);
myPromise
.then(res=>{return result = res;});
result; //output=4

myPromise
.then(res2=>{result = res2 1; return result2=result;});
result2; //output=5

var result;
var result2;
const myPromise = new Promise(
function(resolve)
{
    var a1 = 2   2;
    resolve(a1);
}
);
myPromise
.then(res=>{return result = res;});
result;

myPromise
.then(res2=>{result = res2 1; return result2=result;});
result2;

Here is the info about execute JavaScript and Promise in cefSharp

Evaluate Javascript in the context of this Browsers Main Frame. The script will be executed asynchronously and the method returns a Task encapsulating the response from the Javascript. The result of the script execution in javascript is Promise.resolve so even no promise values will be treated as a promise. Your javascript should return a value. The javascript will be wrapped in an Immediately Invoked Function Expression. When the promise either trigger then/catch this returned Task will be completed.

var script = "return new Promise(function(resolve, reject) { setTimeout(resolve.bind(null, { a: 'CefSharp', b: 42, }), 1000); });"
JavascriptResponse javascriptResponse = await browser.EvaluateScriptAsPromiseAsync(script);

CodePudding user response:

The console.log call just displays the value of the previous statement and nothing more.
Using the result outside the promise function can be a problem - the promise might finish after. Maybe want to look into async/await?

Promise.all does it all

I'm not sure about the C# side of things, but as JavaScript goes:
If you want to access both results of the promises you might be interested in implementing Promise.all

const myPromise = new Promise(
    function(resolve)
    {
        let result = 410;
        resolve(result   10);
    }
);

const myPromise2 = new Promise(
    function(resolve)
    {
        let result2 = 67;
        resolve(result2   2);
    }
);

Promise.all([myPromise, myPromise2]).then((values) => {
  // These are all results from all promises
  // You can analyze/modify/copy their results with a forEach or however you like.
  console.log(values);
});

This example implementation can now use all results from all promises.

  • Related