简体   繁体   中英

How to export result from callback javascript

How to export result from callback javascript to global variable

function capsule (a, b, callback) {
    var res = a + b
    callback( res )
}


capsule(5, 2, n => {
    var result = n
    // console.log(result)
})

// i need do operation with result here, outside the callback
console.log(result) // result is undefined
console.log("ok")

The console back result is undefined

result is only defined inside of your callback. If you define it outside, it will work.

function capsule (a, b, callback) {
    var res = a + b
    callback( res )
}

var result;
capsule(5, 2, n => {
    result = n
})

console.log(result)
console.log("ok")
 capsule(5, 2, n => { var result = n 

var declares a variable that is local to the function.

Declare it outside

var result;

capsule(5, 2, n => {
    result = n

It would probably make more sense to return the value rather than to use a callback though:

function capsule (a, b) {
    var res = a + b;
    return res;
}

var result = capsule(5, 2);
console.log(result);

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