0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

async/awaitの仕組みメモ

Last updated at Posted at 2020-10-01

async/awaitを学習する中で実際に書いて試してみたのでメモ

const makeRequest = (value) => {
  console.log('Request received')
  return new Promise((resolve, reject) => {
    if (value === 'Google') {
      resolve(value)
    } else {
      reject(value)
    }
  }) 
}

const processRequest = (response) => {
  return new Promise((resolve, reject) => {
    console.log('Processing your request...')
    resolve(`Here is the response from ${response}`)
  })
}

const sayHi = async (receiver) => {
  console.log(`Sending request to ${receiver}`)
  const response = await makeRequest(receiver)
  const processedResponse = await processRequest(response)
  console.log(processedResponse);
}

sayHi('Google');
  • 結果
Sending request to Google
Request received
Processing your request...
Here is the response from Google

#async/awaitを使わないとどうなるか

const makeRequest = (value) => {
  console.log('Request received')
  return new Promise((resolve, reject) => {
    if (value === 'Google') {
      resolve(value)
    } else {
      reject(value)
    }
  }) 
}

const processRequest = (response) => {
  return new Promise((resolve, reject) => {
    console.log('Processing your request...')
    resolve(`Here is the response from ${response}`)
  })
}

const sayHi = (receiver) => {
  console.log(`Sending request to ${receiver}`)
  const response = makeRequest(receiver)
  const processedResponse = processRequest(response)
  console.log(processedResponse);
}

sayHi('Google');
  • 結果
Sending request to Google
Request received
Processing your request...
Promise { 'Here is the response from [object Promise]' }

makeRequestのreturnがわかる前にprocessedResponseが走ってしまうため、processedResponseのreturnが先に返ってきてしまい、makeRequestのreturnはPromiseのオブジェクトとだけ記載されてしまう。

async/awaitを使うことで、

  1. makeRequestを待って
  2. processResponseを待って
  3. sayHiを実行することができるようになる

#エラーハンドリング

try/catchがない場合にエラーとなるものを投げる

const makeRequest = (value) => {
  console.log('Request received')
  return new Promise((resolve, reject) => {
    if (value === 'Google') {
      resolve(value)
    } else {
      reject(value)
    }
  }) 
}

const processRequest = (response) => {
  return new Promise((resolve, reject) => {
    console.log('Processing your request...')
    resolve(`Here is the response from ${response}`)
  })
}

const sayHi = async (receiver) => {
  console.log(`Sending request to ${receiver}`)
  const response = await makeRequest(receiver)
  const processedResponse = await processRequest(response)
  console.log(processedResponse);
}

sayHi('Apple');
  • 結果
(node:37639) UnhandledPromiseRejectionWarning: Apple
(Use `node --trace-warnings ...` to show where the warning was created)
(node:37639) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:37639) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

try/catchでエラーの場合の処理

const makeRequest = (value) => {
  console.log('Request received')
  return new Promise((resolve, reject) => {
    if (value === 'Google') {
      resolve(value)
    } else {
      reject(value)
    }
  }) 
}

const processRequest = (response) => {
  return new Promise((resolve, reject) => {
    console.log('Processing your request...')
    resolve(`Here is the response from ${response}`)
  })
}

const sayHi = async (receiver) => {
  try {
    console.log(`Sending request to ${receiver}`)
    const response = await makeRequest(receiver)
    const processedResponse = await processRequest(response)
    console.log(processedResponse);
  } catch {
    console.log("Sorry, we don't communicate with safari")
  }
}

sayHi('Apple');
  • 結果
Sending request to Apple
Request received
Sorry, we don't communicate with safari
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?