【问题标题】:Is it necessary to return a Promise function?是否有必要返回一个 Promise 函数?
【发布时间】: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


【解决方案1】:

您应该返回您的promise(我认为您可以使用promise 来使用某些东西)

但是async不是必须的。

async 标记你应该等待 promise 解决 await

async yourFunction(){
    console.log('Something');
    await readDataBase(); // wait this promise return it's result
    console.log('Oh, done!!!')
}

您的函数返回一个Promise,不要等待它完成。 如果你想等待它,请使用async作为functionParent(这个函数调用你的函数)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-18
    • 1970-01-01
    • 2017-09-13
    • 2020-06-20
    • 2018-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多