Homelab, Linux, JS & ABAP (~˘▾˘)~
 

[SAPUI5] Promisify an oData request

This is discussed for many years and unfortunately will not be implemented in the UI5 framework itself (see here). There are already different blogs describing how to build a wrapper for oData requests (for example here and here).

But with ES2024 it now got super simple to do this:

async function readData(model, entitySet) {
  const [promise, resolve, reject] = Promise.withResolver( )
  model.read(entitySet, {
    success: data => resolve(data),
    error: error => reject(error)
  })
  return promise
}

const user = await readData(oDataModel, "/user")

[JavaScript] Working with Promises in 2024

Since ES2024 there is a new way to create promises by using the withResolver function:

// ES 6 Via Constructor
const promise = new Promise((resolve, reject) => { }

// ES2024 Via factory function
const [promise, resolve, reject] = Promise.withResolver( )

Since ES2018 there is an additional handler called finally:

const promise = fetch("/myAPI")

promise
  .then(response => console.log(response))
  .catch(error => console.error(error))
  .finally(() => console.log("Called in any case"))

And handling multiple Promises has been made easier by the new methods allSettled, any, race which were introduced in ES2020 and ES2015:

// Promise that resolves when all promises are resolved
const promise = Promise.all([promiseA, promiseB])
promise.then(([valueA, valueB]) => console.log(valueA, valueB))

// ES2020 Promise that resolves when all promises are settled (either resolved or rejected)
const promise = Promise.allSettled([promiseA, promiseB])

// ES2020 Promise that resolves when either promiseA or promiseB is resolved
const promise = Promise.any([promiseA, promiseB])

// ES2015 Promise that resolves/rejects when any promise is resolved or rejected
const promise = Promise.race([promiseA, promiseB])