等待承诺从父函数解决

时间:2019-06-07 14:07:36

标签: javascript node.js asynchronous redis

我的节点应用程序中有一个主线程,如下所示:

int

function main_thread() { console.log("Starting"); values = get_values(1); console.log(values); console.log("I expect to be after the values"); } 函数使用node_redis包调用get_values函数。此函数提供了回叫功能,但可以实现以下要求:

hgetall

这对于在函数中的诺言链非常有用,但是在我的主线程中效果不佳,因为我等不及要返回值。

这就是我用红宝石(我使用的主要语言)做的方式:

function get_values(customer_id) {
  // Uses a callback for result
  new Promise(function(resolve, reject) {
    redis_client.hgetall(customer_id, function (err, result) {
    if (err) console.log(err)
      console.log("About to resolve");
      resolve(result);
    });
  })
  .then(({result}) => {
    console.log(result);
  });
}

如何在可重用函数中创建一个Promise,并使主线程等待,直到该函数返回Promise的响应?

编辑:

有人建议可以在主线程中链接def get_values(customer_id) return @redis_client.hgetall(customer_id) end 来返回承诺。但是,这仍然意味着在函数调用之后then块之前,主线程中的所有代码。

编辑2:

与一些IRL JS开发人员朋友进行了长时间的讨论之后,似乎试图创建一个同步脚本违反了现代JS的精神。我将回到我的应用程序设计并致力于使其异步。

3 个答案:

答案 0 :(得分:2)

就像从函数中返回诺言(链)一样简单

function get_values(customer_id) {
  // Uses a callback for result
  return new Promise(function(resolve, reject) {
    redis_client.hgetall(customer_id, function (err, result) {
    if (err) console.log(err)
      console.log("About to resolve");
      resolve(result);
    });
  })
  .then(({result}) => {
    console.log(result);
  });
}

然后在您的主async functionfunction

let result = await get_values();get_values.then(function(result){})

function main_thread() {
  console.log("Starting");
  values = get_values(1).then(function(values){
    console.log(values);
    console.log("I expect to be after the values");
  });
}

async function main_thread() {
  console.log("Starting");
  let values = await get_values(1);
  console.log(values);
  console.log("I expect to be after the values");
}

答案 1 :(得分:1)

返回get_values中的承诺

function get_values(customer_id) {
  // Uses a callback for result
  return new Promise(function(resolve, reject) {
    redis_client.hgetall(customer_id, function (err, result) {
    if (err) console.log(err)
      console.log("About to resolve");
      resolve(result);
    });
  })
  .then(({result}) => {
   reject(result);
  });
}

现在在主线程中,您可以像这样等待它:

function main_thread() {
  console.log("Starting");
  get_values(1).then(function(values) {
    console.log(values);
  }).catch(function(error) {
    console.error(error);
  });
}

答案 2 :(得分:1)

这是async / await的有效示例。我已经用超时和数据数组代替了redis。

async function main_thread() {
  console.log("Starting");
  values = await get_values(1);
  console.log(`After await: ${values}`);
  console.log("I expect to be after the values");
}

async function get_values(customer_id) {
  return new Promise((resolve, reject) => {
      setTimeout(() => {
        const result = [1, 2, 3];
        console.log(`Resolving: ${result}`);
        resolve(result);
      }, 300);
  });
}

main_thread();

进一步阅读: