How to return the result of an asynchronous function in JavaScript

Learn how to use JavaScript to return the result of an asynchronous function (promise-based or callback-based)

Suppose you have this problem: you are making an asynchronous call, and you need to return the result of the call from the original function.

like this:

const mainFunction = () => {
  const result = asynchronousFunction()
  return result
}

butasynchronousFunction()Perform some asynchronous calls in it (e.g.fetch()Call), and the result value cannot be returned directly. Maybe internally it has a promise or callback that needs to be waited for. like this:

const asynchronousFunction = () => {
  return fetch('./file.json').then(response => {
    return response
  })
}

What can you do?

Asynchronous/await is the most straightforward solution. You useawaitKeywords instead of promise-based methods, just like the method we used before:

const asynchronousFunction = async () => {
  const response = await fetch('./file.json')
  return response
}

under these circumstancesmainFunctionWe need to add async to the function signature and wait for the callasynchronousFunction():

const mainFunction = async () => {
  const result = await asynchronousFunction()
  return result
}

Now this will return a promise because it is an asynchronous function:

mainFunction() //returns a Promise

Therefore, to get the result, you can wrap it in IIFE as follows:

(async () => {
  console.log(await mainFunction())
})()

CodeIt looks likeJust like you are used to using synchronous code in other languages, but it is completely asynchronous.

Another way is to use callbacks. But when using async/await, we can just changeasynchronousFunction()Code, in this case we have to

  1. modifyasynchronousFunction()Code
  2. modifymainFunction()Code
  3. Modify the calling code

This is an example.asynchronousFunction()Receive a new function as a parameter, we call itcallback. It calls it to passresponsepurpose:

const asynchronousFunction = callback => {
  return fetch('./file.json').then(response => {
    callback(response)
  })
}

The function passesmainFunction:

const mainFunction = () => {
  const callback = result => {
    console.log(result)
  }

asynchronousFunction(callback) }

The last part of the puzzle is in the called functionmainFunction. Since we can’t directly return a response from itmainFunction, Because we get it asynchronously, so the calling function must change its processing method.

So instead ofconst result = mainFunction(), We can use

const callbackFunction = result => {
  console.log(result)
}

const mainFunction = callback => { asynchronousFunction(callback) }

//call the code mainFunction(callbackFunction)

Download mine for freeJavaScript beginner's manual


More js tutorials: