【问题标题】:how to make node promise method sync?如何使节点承诺方法同步?
【发布时间】:2016-03-27 20:43:15
【问题描述】:

我想做一些准备工作,完成后我的其他工作应该开始,所以我将这些工作称为Q.all,但有些工作是异步的,这就是我想要的。

也许我的代码会让你理解我,在这个简单的例子中我想这样做:

  1. 为数组中的项目调用 foo2
  2. 在 foo2 中,我等待 10 * a ms(假设这是一些已完成的工作),然后更改 res。
  3. 我想 foo2 正在运行然后console.log(res),这意味着所有等待都结束了,所有项目都添加到 res。因此,在我的示例中, res 更改为 6。

这里是代码

var Q = require("q");
var res = 0;
function foo(a) {
  res += a;
}

function foo2(a) {
  // this is a simple simulation of my situation, this is not exactly what I am doing. In one word, change my method to sync is a little bit difficult
  return Q.delay(10 * a).then(function() {
    res += a;
  });
}

// Q.all([1, 2, 3].map(foo)).done(); // yes, this is what I want, this log 6

// however, because of some situation, my work is async function such as foo2 instead of sync method.
Q.all([1, 2, 3].map(function(a) {
  return foo2(a);
})).done();
console.log(res); // I want 6 instead of 0

【问题讨论】:

  • 你不应该在你的 foo2 函数中 return Q.delay(10*a) 吗?
  • 我需要用a在foo2做一些更复杂的工作,但我只是举一个简单的例子,比如res += a,我只想指出foo2是异步的!跨度>
  • 你的问题到底是什么?
  • 在 foo2 中,您没有返回承诺。你应该return Q.delay(10*a)...,它会返回一个承诺。
  • 是的,你有什么问题?

标签: node.js asynchronous synchronization promise


【解决方案1】:

您正在混合同步和异步编程风格。

在这种情况下,您的console.log 语句将在任何承诺有时间履行之前运行(在res 被他们修改之前),因为它不在承诺块内。

在此处查看在 promise 解决后如何运行 console.log

var Q   = require("q"),
    res = 0;


function foo(a) { res += a; }

function foo2(a) {
  return Q
    .delay(10 * a)
    .then(function() { res += a; });
}

Q.all( [1, 2, 3].map(function(a) { return foo2(a); }) )
.then(function(){ console.log(res) })
.done();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-08
    • 2019-07-14
    • 2017-11-03
    • 2016-12-16
    • 2021-06-18
    • 2016-05-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多