我写了一个Promise函数,将Object的Object转换为Array of Object:
function objectToArray(objectOfObject) {
return new Promise((resolve,reject) => {
var newArray = Object.keys(objectOfObject).map(key => {
let object = objectOfObject[key]
object['id'] = key
return object;
})
resolve(newArray)
reject('error')
})
}
因此,我的解析将返回一个object数组,但是如果objectOfObject
不是Object的对象,我如何使用reject返回TypeError,我相信这会导致typeerror?
谢谢。
发布于 2018-05-09 04:30:21
您可以使用if...else
function objectToArray (objectOfObject) {
return new Promise((resolve, reject) => {
if (typeof objectOfObject === 'object') {
var newArray = Object.keys(objectOfObject).map(key => {
let object = objectOfObject[key]
object['id'] = key
return object
})
resolve(newArray)
} else {
reject(new TypeError())
}
})
}
或者使用try... catch
function objectToArray (objectOfObject) {
return new Promise((resolve, reject) => {
try {
var newArray = Object.keys(objectOfObject).map(key => {
let object = objectOfObject[key]
object['id'] = key
return object
})
resolve(newArray)
} catch (error) {
reject(error)
}
})
}
发布于 2018-05-09 04:31:12
我想你可能想把这个错误作为Error
的一个实例:
reject(new Error('error'))
发布于 2018-05-09 04:47:32
function objectToArray (objectOfObject) {
return new Promise((resolve, reject) => {
if (typeof objectOfObject !== 'object') {
reject(new TypeError())
}
var newArray = Object.keys(objectOfObject).map(key => {
let object = objectOfObject[key]
object['id'] = key
return object
})
resolve(newArray)
})
}
https://stackoverflow.com/questions/50245407
复制