JS

Donburi·2023년 2월 12일
0

자기개발

목록 보기
2/2

JS

All under an async context such as an express route
typical fetch

fetch('someURL', {
        method: 'GET',
        headers: {}
    })
    .then(response => response.json())
    .then(data => {
        return res.status(200).json({
            success: true
          	processed: process(data)
        })
    })
    .catch(e => {
        return res.status(500).json({
            success: false,
          	error: e.toString()
        })
    })

the equivalent using await

try {
        let response = await fetch('someURL', {
            method: 'GET',
            headers: {}
        })
        let data = await response.json()
			
        return res.status(200).json({
            success: true
          	processed: process(data)
        })
} catch (e) {
        return res.status(500).json({
          success: false,
          error: e.toString()
        })
}

multiple promises (fetches)

await Promise.all(
        stuffs.map(async(stuff) => {
            try {
                let response = await fetch('someURL', {
                    method: 'GET',
                    headers: {}
                })
                let data = await response.json()
                
                // do something with data
            } catch (e) {
                return res.status(500).json({
                  success: false,
                  error: e.toString()
                })
        })
    );

0개의 댓글