Node.js中的C ++ future async等价物

时间:2017-10-01 19:02:53

标签: c++ node.js

我想在Node.js中编写以下C ++代码。

#include <iostream>
#include <future>
#include <string>

std::mutex mut;

void print(const std::string& message, int n) {
    for (int i = 0; i < n; ++i) {
        {
            std::lock_guard<std::mutex> lk(mut);
            std::cout <<  message << std::endl;
        }
        usleep(200000);
    }
    std::lock_guard<std::mutex> lk(mut);
    std::cout << message << " finished" << std::endl;;
}

int main() {
    std::future<void> fut_a = std::async(print, "a", 2);
    std::future<void> fut_b = std::async(print, "b", 8);
    fut_a.get();
    std::future<void> fut_c = std::async(print, "c", 2);
    std::future<void> fut_d = std::async(print, "d", 2);
    fut_c.get();
    fut_d.get();
    fut_b.get();

}

输出为:a b a b b c d b d c b b b b

在Node.js v8.6.0中,以下代码在显示“a”完成之前开始显示“c”。

const asyncfunc = (message, n) => {
    for (let i = 0; i < n; ++i) {
        setTimeout(() => {
            console.log(message);
        }, 200 * i);
    }
}

async function main() {
    const a = asyncfunc("a", 2);
    const b = asyncfunc("b", 8);
    await a;
    const c = asyncfunc("c", 2);
    const d = asyncfunc("d", 2);
    await c;
    await d;
    await b;
}

main();

输出为:a b c d a b c d b b b b b

Node.js中是否有方便编写上述C ++代码的方法?

1 个答案:

答案 0 :(得分:0)

您的asyncfunc必须返回Promise

const asyncfunc = (message, n) => {
  const promises = [];
  for (let i = 0; i < n; ++i) {
    promises.push(new Promise((resolve) => {
      setTimeout(() => {
        resolve(message);
        console.log(message);
      }, 200 * i);
    }));
  }
  return Promise.all(promises);
};