JavaScript – How to write code cleaner with Async/ Await?

How to use Async/ Await with async function having callback?

Not using Async/ Await

var successCallback = function(responseNewUri) {
    // Do something with responseNewUri
    // ...
}

var errorCallback = function(error) {
    alert('Error: ', error)
}

// Convert the "content://" into "file://"
const uri = "content://xxxxx"
window.FilePath.resolveNativePath(fileUri, successCallback, errorCallback);

Using Async/ Await

// Create promise method
const promiseResolveFilePath = (uri) => {
    const promise = new Promise((resolve, reject) => {
        const successCallback = (responseNewUri) => {
            resolve(response)
        }

        const errorCallback = (error) => {
            reject('NG')
        }

        window.FilePath.resolveNativePath(fileUri, successCallback, errorCallback)
    })

    return promise
}

// Usage
try {
    const uriResolved = await promiseResolveFilePath(uri)
    if (uriResolved !== 'NG') {
        // Success to "resolveNativePath", do something with new uriResolved
        ...
    } else {
        // Fail to "resolveNativePath"
        ...
    }
} catch(error) {
    // Reject value comes here 
}

How to use Promise in “reduce”?

const result = await list.reduce(async (newArray, element) => {
      // Some await process here
      ...

      // Then
      newArray.push({
         "id": 1,
         "name": "ABC"
      })

      return newArray
 }, [])

console.log(result)  // Promise <pending>

You have to use Promise returning version

const result = list.reduce(async (newArray, element) => {
      const newSetArray = await newArray
 
      // Some await process here
      ...

      // Then
      newSetArray.push({
         "id": 1,
         "name": "ABC"
      })

      return newSetArray
 }, [])


console.log(result)

How to get return value from an async function?

Async function always returns Promise

async function hello() {
  return 'Hello Alligator!';
}

hello()
.then(x => console.log(x)); // Hello Alligator!
.catch(x => console.log(x)) // unhandled errors

Can I use async/await in loop?

It works with most loops (while, for-of, …) but won’t work with loops that require a callback (forEach, map, filter, …)

Be the first to comment

Leave a Reply

Your email address will not be published.


*