Created
March 1, 2021 14:20
-
-
Save brunocarvalhodearaujo/30abc21b81eb9aebc8583ae13732fd79 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Copyright (c) 2021-present, Bruno Carvalho de Araujo. | |
* All rights reserved. | |
* | |
* This source code is licensed under the license found in the LICENSE file in | |
* the root directory of this source tree. | |
*/ | |
import fetch from 'cross-fetch' | |
export const downloadItem = async () => { | |
try { | |
const response = await fetch('http://slowwly.robertomurray.co.uk/delay/10000/url/http://google.co.uk') | |
if (!response.ok) { | |
throw Error('Api error!') | |
} | |
return response.status | |
} catch (error) { | |
return Promise.reject(error) | |
} | |
} | |
/** | |
* @param {Promise<any>} promise | |
* @param {number} [milliseconds] | |
*/ | |
export const promiseWithTimeout = (promise, milliseconds = 3000) => { | |
// Esta promise fará a rejeição da Promise dentro do tempo (ms) definido | |
const timeout = new Promise((resolve, reject) => { | |
setTimeout(() => { | |
reject(new Error(`Promise timeout reached (limit: ${milliseconds} ms)`)) | |
}, milliseconds) | |
}) | |
// Faz uma corrida entre a Promise que desejamos resolver com a promise com o timeout definido | |
return Promise.race([timeout, promise]) | |
} | |
;(async () => { | |
const test = await promiseWithTimeout(downloadItem()) | |
console.info(test) | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment