Как можно перезаписать ответ от fetch в переменную?

const URL = 'https://jsonplaceholder.typicode.com/users'

const request = (method, url, body = null) =>{
    return fetch(url, {
        method: method,
        body: body
    }).then(request => {
        return request.json()
    })
}

a = request('GET', URL).then(data =>{
    return data
})

console.log(a )
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
    <script src="fetch.js"></script>
</body>
</html>


Ответы (1 шт):

Автор решения: HTO HOT

fetch это асинхронный метод который возвращает Promise. Соответственно код ,который идёт после вашего вызова функции request, сработает раньше, чем сам request. Поэтому делайте либо так

const URL = 'https://jsonplaceholder.typicode.com/users'

const request = (method, url, body = null) =>{
    return fetch(url, {
        method: method,
        body: body
    }).then(request => {
        return request.json()
    })
}
request('GET', URL).then(data =>{
    let a=data;
    console.log(data)
})

Либо так

const URL = 'https://jsonplaceholder.typicode.com/users'

const request = (method, url, body = null) =>{
    return fetch(url, {
        method: method,
        body: body
    }).then(request => {
        return request.json()
    })
}

const start = async ()=>{
 let a = await request('GET', URL)
 console.log(a)
}
start()

→ Ссылка