两条平行的通话一方在JavaScript成功 [英] two parallel calls either one succeeds in javascript

查看:159
本文介绍了两条平行的通话一方在JavaScript成功的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想是这样的异步库做两个平行要么调用javascript中有一个人成功,然后回调的成功输出操作。它似乎并不认为异步有。 平行会犯错是否任何一个失败。

I want something like the async library to do two parallel calls either one succeeds in javascript and then the callback to operate on the succeeded output. It does not seem that async has that. parallel would err out if either one fails.

在一般情况下,如果我有 N 任务,我要保证 M 成功,并使用从输出这些 M 电话,我该怎么办呢?

In general, if I have N tasks, and I want to guarantee m succeed and use the output from these m calls, how can I do it?

推荐答案

您想 Promise.race (假设你是愿意从异步移至承诺):

Promise.race

You want Promise.race (assuming you are willing to move from async to promises):

Promise.race([d1, d2]) . then(result =>

MDN :

Promise.race 方法返回解析后,或在迭代解决了承诺之一拒绝或拒绝,从这一承诺的价值或理由的承诺

The Promise.race method returns a promise that resolves or rejects as soon as one of the promises in the iterable resolves or rejects, with the value or reason from that promise.

据我可以看到异步不提供比赛的相当,但你可以这样做:

Writing race in callback fashion

As far as I can see async does not provide the equivalent of race, but you can do something like:

async.race = function(tasks, callback) {
  var done = false;
  tasks.forEach(function(task) {
    task(function(err, data) {
      if (done) return;            // another task finished first
      done = true;
      callback(err, data);
    });
  });
};

也许你想比赛,其中错误被忽略的一个变种 - 虽然说设计似乎值得商榷。在这种情况下:

Perhaps you want a variant of race where errors are ignored--although that design seems questionable. In that case:

async.firstFulfilled = function(tasks, callback) {
  var done = false;
  tasks.forEach(function(task) {
    task(function(err, data) {
      if (err || done) return;    // skip failures
      done = true;
      callback(err, data);
    });
  });
};

返回第一的 N 的非错误情况:

async.firstNFulfilled = function(n, tasks, callback) {
  var result = [];
  tasks.forEach(function(task) {
    task(function(err, data) {
      if (err) return;
      result.push(data);
      if (!--n) callback(null, result);
    });
  });
};

这篇关于两条平行的通话一方在JavaScript成功的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆