简体   繁体   English

异步/等待回调后如何为全局变量赋值

[英]how can I assign value to global variable after Async/await call back

JSFiddle example https://jsfiddle.net/xo15vet6/

I want to process the Async function result to another function, Once user click the save button I should process global variable value, how can I achieve it.我想将异步 function 结果处理到另一个 function,一旦用户单击保存按钮,我应该处理全局变量值,我该如何实现。

getMovieAsync is a function, not a promise getMovieAsync是 function,而不是 promise

I think this will work:我认为这会起作用:

let finalMovies = "";
async function getMovieAsync() {
    const response = await fetch('https://www.omdbapi.com/?s=batman&y=&plot=short&r=json');
    const movies = await response.json();
    return movies;
}

finalMovies = getMovieAsync();
console.log("final movies " + finalMovies);

For what I see you should be already be doing it, in the case you wanted to assign the value to finalMovies, what is happening is that the second console.log is getting executed right after the call to that is asynchronous function so it will execute and then go to the next line (the console.log), but the console.log that is in the.then will only get there if the async operation resolves.对于我看到的你应该已经这样做了,如果你想将值分配给 finalMovies,发生的事情是第二个 console.log 在调用异步 function 之后立即执行,所以它将执行然后 go 到下一行(console.log),但只有在异步操作解决时,.then 中的 console.log 才会到达那里。 If somehow it it rejects it will not even print that line.如果它以某种方式拒绝它甚至不会打印该行。 Because it will go to the.catch of the async function.因为它将 go 到异步 function 的.catch。

    let finalMovies = "";
        async function getMovieAsync() {
            var response = await fetch('https://www.omdbapi.com/?s=batman&y=&plot=short&r=json');
            var movies = await response.json();
            return movies;
        }
async function getMovies(){

        try{
           finalMovies = await getMovieAsync();
           console.log("final movies', finalMovies);
        }catch(exception){
           console.log('Something went wrong')
        }
}

if you pay attention I changed the second console log because if you do the "string" + (something that might be an object or array of object) it will print you the [object Object] because it will run the default toString() for that.如果您注意我更改了第二个控制台日志,因为如果您执行“字符串”+(可能是 object 或对象数组),它将为您打印 [object Object],因为它将运行默认的 toString()那。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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