从回调中获取空承诺

问题描述 投票:0回答:1

谁能告诉我为什么在这种情况下,我得到一个空的承诺? Promise { undefined }我在返回之前看到了 console.log 的数据,所以它没有抛出任何错误。

const getObj = async (bucket, path) => {
  try {
    let timer = us.now();
    time_log('info', util.format('Getting object'));
    minioClient.getObject(bucket, path, function(err, stream) {
      if (err) { _throw({ code: 'internal_error', severity: 1, user_code: 'internal_error', reason: util.format('unhandled_exception occured in getObj function: %s', err)}) };
      let buffer = '';
      stream.on('data', function(chunk) {
        buffer += chunk;
      })
      stream.on('end', function() {
        time_log('mile', util.format('getObj response_took: [%s]', us.parse((us.now() - timer)).toString()));
        return(JSON.parse(buffer));
      })
      stream.on('error', function(err) {
        throw(err);
      })
    })
  }
  catch (e) {
    throw({ code: 'internal_error', severity: 1, user_code: 'internal_error', reason: util.format('unhandled_exception occured in getObj function: %s', e)});
  }
}

console.log(getObj('configs', 'nodes.json'));
javascript node.js asynchronous
1个回答
1
投票

async 函数应该返回承诺。在你的例子中,你没有返回任何东西。你可以这样做。

const getObj = async (bucket, path) => {
try {
    let timer = us.now();
    time_log('info', util.format('Getting object'));
    return new Promise((resolve, reject) => {
      minioClient.getObject(bucket, path, function(err, stream) {
          if (err) { reject({ code: 'internal_error', severity: 1, user_code: 'internal_error', reason: util.format('unhandled_exception occured in getObj function: %s', err)}) };
          let buffer = '';
          stream.on('data', function(chunk) {
            buffer += chunk;
          })
          stream.on('end', function() {
            time_log('mile', util.format('getObj response_took: [%s]', us.parse((us.now() - timer)).toString()));
            resolve(JSON.parse(buffer));
          })
          stream.on('error', function(err) {
            reject(err);
          })
      })
    })
  }
  catch (e) {
    throw({ code: 'internal_error', severity: 1, user_code: 'internal_error', reason: util.format('unhandled_exception occured in getObj function: %s', e)});
  }
}

console.log(getObj('configs', 'nodes.json'));
© www.soinside.com 2019 - 2024. All rights reserved.