[Javascript]How to save a fetch result into a variable


Commonly, fetch method is executed asynchronously, and some operation against the result is done in the then method.

In this article, I am going to describe about how to save a fetch result into a variable without using the then method.




Common usage of fetch method

Commonly, fetch method is used as below.
In this way, we have to write the continuation in the then method.

const url = 'http://fuga.com/img/sample.png'
fetch(url)
.then(response => {
    //operation against response
})




Trying to fetch without then method

When you try to fetch without then method, you may come up with below code.
But it does not work.

Promise object would come in the response variable.

const url = 'http://fuga.com/img/sample.png'
response = fetch(url)
console.log(response)        //Promise object




Correct way to save a fetch result into a variable

By using async/await, you can save a fetch result into a variable.
Response object would come in the response variable.

;(async function() {
    const url = 'http://fuga.com/img/sample.png'
    response = await fetch(url)
    console.log(response)        //Response object
})()



await is only available in the async function. In the above code, I have used the async function as IIEF(immediately invoked function expression) by putting () at the last line.
When you want to use await, maybe you can try to enclose all code with async IIEF. (like below)

;(async function() {
    //some code
    //some code
    //some code
    //some code

    const url = 'http://fuga.com/img/sample.png'
    response = await fetch(url)

    //some code
    //some code
    //some code
    //some code
})()




Fetch as blob data

A short while ago, we tried to fetch as response object which has header infomation and so on.
We can also fetch as blob data by wrhiting as below.

let blob = await (await fetch(url)).blob()




Using fetch as a function

You can use fetch as a function.

async function url2Blob(url) {
    return (await fetch(url)).blob()
}


You can use it as below.

;(async function() {
    //some code
    //some code
    //some code
    //some code

    const url = 'http://fuga.com/img/sample.png'
    const blob = await url2Blob(url)

    //some code
    //some code
    //some code
    //some code
})()


async function url2Blob(url) {
   return (await fetch(url)).blob()
}





That is all. It was about how to save a fetch result into a variable.

You can subscribe by SNS

Sponcerd Link

Popular Posts

*