Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

异步编程-Promise 题目 5 - 5 #142

Open
leslie1943 opened this issue Jan 12, 2021 · 0 comments
Open

异步编程-Promise 题目 5 - 5 #142

leslie1943 opened this issue Jan 12, 2021 · 0 comments

Comments

@leslie1943
Copy link
Owner

leslie1943 commented Jan 12, 2021

Promise 5 - 5

  • async1await 后面的 Promise 是没有返回值的, 也就是它的状态始终是 pending 状态, 因此相当于一直在 await, await, await 却始终没有响应.
  • 所以在 await 之后的内容是不会执行的, 也包括 async1 后面的 .then.

如果在一个 Promise 前使用了 await, 那么一定要 resolve('OK') / reject('Error') 不然会一直 await , 阻挡后面语句的执行.

async function async1() {
  console.log('async1 start')
  await new Promise((resolve) => {
    console.log('promise1')
    // ✅✅ 此处需要 reslove
  })
  console.log('async1 success')
  return 'async1 end'
}
console.log('srcipt start')

async1().then((res) => console.log(res))

console.log('srcipt end')

/**
 * srcipt start
 * async1 start
 * promise1
 * srcipt end
 */

在async1的await后设置返回

async function async1() {
  console.log('async1 start')
  await new Promise((resolve) => {
    console.log('promise1')
    resolve('value in async1 await') // 这一行的结果没有被接收
  })
  console.log('async1 success')
  return 'async1 end' // 直接返回了字符串 .then(res) 中的 res的值
}
console.log('srcipt start')

async1().then((res) => console.log(res))

console.log('srcipt end')

/**
 * srcipt start
 * async1 start
 * promise1
 * srcipt end
 * async1 success
 * async1 end
 */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant