【发布时间】:2018-08-27 09:22:38
【问题描述】:
如果我在 Node 8+ 中使用 await & async,是否需要返回 Promise 函数?
async function _readSourceDataFromCache (slug_name) {
aerospikeClient = aerospikeConf.AerospikeClient;
console.log('In async function')
console.log(aerospikeClient);
return new Promise ( function (resolve, reject) {
aerospikeClient.get(aerospikeConf.AerospikeKey, function (error, record) {
if (error) {
switch (error.code) {
case aerospikeConf.Aerospike.status.AEROSPIKE_ERR_RECORD_NOT_FOUND:
console.log('NOT_FOUND -', aerospikeConf.AerospikeKey)
break
default:
console.log('ERR - ', error, aerospikeConf.AerospikeKey)
}
resolve(false)
}
else{
resp = record['value']
aerospikeClient.close();
return resolve(resp);
}
});
})
}
如何从调用函数处理这个问题?
【问题讨论】:
-
我需要在调用函数中使用 try/catch 块吗?
-
虽然
async函数自然已经返回 Promises,但看起来您需要显式构造Promise以便将aerospikeClient.get调用转换为 Promise 而不是回调。 -
恕我直言,这太短了,无法回答,但您可以这样处理:
_readSourceDataFromCache(something).then(callback_function)
标签: node.js promise async-await