const isOutInet = async () => {
const urlAll = ['https://www.google.com/', 'https://www.baidu.com/']
let baseUrl = null
for (let i = 0; i < urlAll.length; i++) {
try {
await new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
baseUrl = urlAll[i]
reject()
} else {
resolve()
}
}
}
xhr.open('post', urlAll[i])
xhr.send()
})
} catch (e) {
console.error(e)
break
}
}
return baseUrl
}
isOutInet().then((val) => {
console.log(val)
})
isOutInet()
方法返回的值是一个Promise
,可以用回调方法then
来取里面的返回值Promise
只有在执行到resolve()
或reject()
才返回,resolve()
是标记成功返回,reject()
是标记错误返回resolve()
括号里可以放返回值,reject()
同理