This README and library is still in early development stage. Please be aware that some breaking changes can be introduced in future versions. Thank YOU!
TODO: Description
- Inspiration
- Install
- Functions
TODO: Inspiration
-
npm
npm install shy-sloth
-
yarn
yarn add shy-sloth
-
pnpm
pnpm add shy-sloth
TODO: List of functions
When promise resolved to undefined
, then default value will be used. Remember that default value is actually function that returns default value.
TODO: Describe the reason of using function
Examples:
const promise = async () => undefined
const foo = withDefault(
promise,
() => 'DEFAULT_VALUE'
)
await foo() // 'DEFAULT_VALUE'
You can pass arguments to promise like this:
const promise = async (name) => name ? `Hello ${name}` : undefined
const foo = withDefault(
promise,
() => "What's your name?"
)
await foo('John') // 'Hello John'
await foo(null) // "What's your name?"
When promise resolves, the resolved value is used as a key, to get property from provided object.
Examples:
const statusToText = {
200: 'OK',
404: 'Not Found'
}
const promise = async (url) => {
return fetch(url).then(r => r.status)
}
const getTextFromStatus = withMappedResult(
promise,
statusToText
)
await getTextFromStatus('https://...') // 'OK'
You can always make use of withDefault and withMappedResult to provide information even when status was not mapped:
const statusToText = {
200: 'OK',
404: 'Not Found'
}
const promise = async (url) => {
return fetch(url).then(r => r.status)
}
const getTextFromStatus = withDefault(
withMappedResult(promise, statusToText),
() => "???"
);
// Status: 200
await getTextFromStatus('https://...') // 'OK'
// Status: 201
await getTextFromStatus('https://...') // '???'
Why no built in default value in withMappedResult? Shy-sloth target is to provide as simple as possible functions, that can work well together. You can see how easy was to add withDefault. There were even no changes needed in code. I've just added withDefault on top of withMappedResult.
Let's be honest. If you don't like this approach, the shy sloth, is totally fine with that. He's sleeping anyways. 🦥