0

There are two functions; function getThumbnail(url) {} and function getVimeoData() {}.

I'm using fetch() to handle the HTTP calls for retrieving the url of thumbnail of a video in Vimeo. oEmbed is used to fetch JSON data of a video, which contains thumbnail_url.

The functions goes as follow:

async function getVimeoThumb(videoUrl) {
    return await fetch(videoUrl)
        .then(response => {
            if (response.status !== 200) {
                console.log('Error occurred while fetching thumbnail.');
                return null;
            }

            return response.json();
        })
        .then(data => {return data['thumbnail_url']})
        .catch(err => console.log(err.reason));
}

The above function returns Promise with a value [[PromiseValue]]: "{{thumbnail_url}}". The returned Promise value is fetched in following function as:

function getThumbnailUrl() {
    let newUrl;

    ...

    getVimeoThumb(url).then(result => {console.log(result)})

    ...
}

The above function returns console log as {{thumbnail_url}}.

Hence, my question is that is there any workaround to store the fetched value {{thumbnail_url}} in my local variable newUrl?

Pa-won
  • 165
  • 1
  • 2
  • 10
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – str Nov 14 '18 at 09:27

2 Answers2

0

You already have a local variable (newUrl), so where you are logging the result you can save there only

function getThumbnailUrl() {
    let newUrl;

    ...

    getVimeoThumb(url).then(result => { newUrl = result; console.log(result) })

    ...
}
Nitish Narang
  • 4,124
  • 2
  • 15
  • 22
  • 1
    While this might work in theory, it is not usable in practice. You don't know *when* `newUrl` is actually defined. The correct answer to this question can be found in the duplicate. – str Nov 14 '18 at 09:28
  • I get that @str . Though not clearly stated in OP that async is causing trouble or not getting proper response from async calls rather it was menitioned that results are coming just needed to save to local variable. Still it looks your insight could be correct on this. Thnx – Nitish Narang Nov 14 '18 at 10:49
0

@Nitich is right. But if what you want is use newUrl out side you can try this. newUrl will be in the global scope.

    let newUrl;
    function getThumbnailUrl() {

    ...

    getVimeoThumb(url).then(result => { newUrl = result; console.log(result) })

    ...
    }

Or simply do

    ...

    getVimeoThumb(url).then(result => { newUrl = result; return newUrl; })

    ...
    }
    let newUrl = getThumbnailUrl(videoUrl);

I hope this helps.

  • No he is not quite right. Your first example has the same limitations as his. And the second example will return a promise, not the URL. – str Nov 14 '18 at 10:45