The thing you have to understand is that once you step into the future ("I promise that this will eventually return a value"), you will never get back into the boring and safe world of synchronous step-by-step processing.
// It does not matter what you do inside this function or
// what you return. Because of the await keyword, this will
// **always** return a promise.
//
getCustomerById: async (id) => { /* ... */ }
The promise is a container, and you can pass that container around all you want. But to look inside the container you need to use a callback.
(Or use async
/await
, which is just syntactic sugar for .then
. Under the hood it calls .then
for you, with the remaining code left in your async
function as the callback.)
So to get at the result, you need to wait for the promise to resolve. That leaves you with 2 choices: .then
or await
.
const apiKey = 'some_crazy_long_string_you_got_from_somewhere_safe'
const baseUrl = 'http://www.ready.buzlin.com/buzlinApp/customer'
// Let's show the object this is attached to, so we can
// actually make calls to the function.
//
const customerQueries = {
getCustomerById: async (id) => {
const url = `${baseUrl}/getCustomerById.php?k=${apiKey}&id=${id}`
let response
try {
response = await fetch(url)
return response.json()
} catch (err) {
// ... Properly handle error
// If you are not going to properly handle this error, then
// don't catch it. Just let it bubble up.
}
}
}
// Or a cleaner looking alternative that is also more true to the
// underlying behavior by skipping all this `async/await` nonsense.
//
const customerQueries2 = {
getCustomerById: (id) => {
const url = `${baseUrl}/getCustomerById.php?k=${apiKey}&id=${id}`
return fetch(url)
.then(response => response.json())
.catch(err => {
// ... Properly handle error
})
}
// Now to get at the result
//
// Using .then
customerQueries.getCustomerById(27)
.then(customer => {
//
// ... Do something with customer
//
})
// Or using async/await
(async () => {
const customer = await customerQueries.getCustomerById(27)
//
// ... Do something with customer
//
})()