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化的confirm 应该总是 resolved #15

Open
fisker opened this issue Oct 26, 2018 · 0 comments
Open

promise化的confirm 应该总是 resolved #15

fisker opened this issue Oct 26, 2018 · 0 comments

Comments

@fisker
Copy link
Owner

fisker commented Oct 26, 2018

一些ui库把 confirm 设计成 类似

function badConfirm(msg) {
  return window.confirm(msg)
    ? Promise.resolve(true)
    : Promise.reject(true)
}

那么使用的时候就可以

badConfirm('你确认吗?')
  .then(() => console.log('确认'))
  .catch(() => console.log('取消'))

看起来很美好,直到你使用 await 的时候

(async () => {
  let ok = false

  try {
    ok = await badConfirm('你确认吗?')
  } catch (err) {}
  console.log(ok ? '确定' : '取消')
})()

因为你不用 try/catch 你的程序就报错了

写一两次可能还好,当你需要反复确认的时候,只有一个感觉想死

所以我推荐返回的primise总是resolved

async function goodConfirm(msg) {
  return await window.confirm(msg)
}

// OR

function goodConfirm(msg) {
  return new Promise(resolve => resolve(window.confirm(msg)))
}

// OR

function goodConfirm(msg) {
  return Promise.resolve(window.confirm(msg))
}

then 语法

goodConfirm('你确认吗?')
  .then(ok => console.log(ok ? '确认' : '取消'))

await 语法

(async () => {
  let ok = await goodConfirm('你确认吗?')
  console.log(ok ? '确定' : '取消')
})()
@fisker fisker changed the title confirm should always resolve promise化的confirm 应该总是 resolve Oct 26, 2018
@fisker fisker changed the title promise化的confirm 应该总是 resolve promise化的confirm 应该总是 resolved Oct 26, 2018
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