0
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.

Sampath
  • 11
  • 1
  • 3

2 Answers2

0

getMovieAsync is a function, not a 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);
Cesar
  • 417
  • 5
  • 17
0

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. If somehow it it rejects it will not even print that line. Because it will go to the .catch of the async function.

    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.