javascript 与异步等待的承诺
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 与异步等待的承诺相关的知识,希望对你有一定的参考价值。
const fetchData = ((id) => {
let candidate = [{ "name": "Jamal", "age": "29", "gender": "male"},
{ "name": "Sandra", "age": "21", "gender": "remale"},
{ "name": "Greg", "age": "29", "gender": "male"}]
return new Promise((resolve, reject) => {
setTimeout(() => {
if (id !== undefined && id <= candidate.length -1) {
resolve(candidate[id])
} else {
reject("Ooops!, user not found: You must provide a valid userId")
}
}, 1000)
})
})
async function dataCall2(userId) {
const candidate = await fetchData(userId)
for (var key in candidate) {
if (candidate.hasOwnProperty(key)) {
console.log(key.toUpperCase() + ": " + candidate[key])
}
}
}
dataCall2(2).catch(e => {
console.log(e)
})
以上是关于javascript 与异步等待的承诺的主要内容,如果未能解决你的问题,请参考以下文章
javascript 承诺和异步等待
javascript 回调,承诺,异步/等待
javascript 回调,承诺和异步/等待
javascript 承诺和异步等待
承诺等待得到解决而不返回
使用异步/等待与承诺的区别?