Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/477.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript node.js:如何使用sequence和promise对两个aync循环建模_Javascript_Node.js_Asynchronous_Promise_Sequence - Fatal编程技术网

Javascript node.js:如何使用sequence和promise对两个aync循环建模

Javascript node.js:如何使用sequence和promise对两个aync循环建模,javascript,node.js,asynchronous,promise,sequence,Javascript,Node.js,Asynchronous,Promise,Sequence,我在node.js中有两个函数,让我们称它们为func_A和func_B,它们都需要在循环中被调用,但这需要一个接一个地发生 首先,func_a需要在循环中被调用num1次 for (i=0; i<num1; i++) { func_a(i, function(err,cb1)) } for(i=0;i您可以使用Promise并在其中封装异步函数。 我没有测试它,但逻辑应该是可行的 let _func_a = (i) => { return new

我在node.js中有两个函数,让我们称它们为func_A和func_B,它们都需要在循环中被调用,但这需要一个接一个地发生

首先,func_a需要在循环中被调用num1次

for (i=0; i<num1; i++)
{
    func_a(i, function(err,cb1))
}

for(i=0;i您可以使用Promise并在其中封装异步函数。
我没有测试它,但逻辑应该是可行的

let _func_a = (i) => {
            return new Promise(function (resolve, reject) {
                func_a(i, function (err, res) {
                    if (err) {
                        return reject(err);
                    }
                    return resolve(res);
                    })
            })
    }   
    let _func_b = (j) => {
            return new Promise(function (resolve, reject) {
                func_b(j, function (err, res) {
                    if (err) {
                        return reject(err);
                    }
                    return resolve(res);
                    })
            })
    }   
    (async function loop() {
        try {
            for (i=0; i<num1; i++){
                let a = await _func_a(i)
            }
            for (j=0; j<num2; j++){
                let b = await _func_b(j)
            }
        console.log("here you're sure both for loops are done")
        } catch(err) {
            console.error("some error has occurred")
        }
    })();
let\u func\u a=(i)=>{
返回新承诺(功能(解决、拒绝){
函数a(i,函数(err,res){
如果(错误){
退货拒绝(err);
}
返回解析(res);
})
})
}   
设_func_b=(j)=>{
返回新承诺(功能(解决、拒绝){
函数b(j,函数(err,res){
如果(错误){
退货拒绝(err);
}
返回解析(res);
})
})
}   
(异步函数循环(){
试一试{

对于(i=0;i在制作了
func_a()
func_b()
的预期版本后,您可以在中使用和聚合结果,而无需使用计数器:

const promisify = fn => function () {
  return new Promise((resolve, reject) => {
    // forward context and arguments of call
    fn.call(this, ...arguments, (error, result) => {
      if (error) {
        reject(error)
      } else {
        resolve(result)
      }
    })
  })
}

const func_a_promisified = promisify(func_a)
const func_b_promisified = promisify(func_b)

async function loop_a_b (num1, num2) {
  // await pauses execution until all asynchronous callbacks have been invoked
  const results_a = await Promise.all(
    Array.from(Array(num1).keys()).map(i => func_a_promisified(i))
  )

  const results_b = await Promise.all(
    Array.from(Array(num2).keys()).map(j => func_b_promisified(j))
  )

  return {
    a: results_a,
    b: results_b
  }
}

// usage
loop_a_b(3, 4).then(({ a, b }) => {
  // iff no errors encountered
  // a contains 3 results in order of i [0..2]
  // b contains 4 results in order of j [0..3]
}).catch(error => {
  // error is first encountered error in chronological order of callback results
})
为了简化
Array.from(…).map(…)
mess,您可以编写一个助手来同时调用异步函数:

function * loop_fn_n (fn, n) {
  for (let i = 0; i < n; i++) {
    yield fn(n)
  }
}

正如所指出的,我在这里实现的
promisify
功能也可以在Node.js核心模块中使用。

您尝试过吗

您提到的代码可能会转换为以下内容:

// Dependencies.
const util = require('util');

// Promisify your functions.
const func_a_as_promise = util.promisify(func_a);
const func_b_as_promise = util.promisify(func_b);

// Now we may create 'async' function with 'await's.
async function doSomething() {
  // Some data containers if you need any (?).
  const someDataA = [];
  const someDataB = [];

  // First async loop that looks like sync one.
  for (i=0; i < num1; i++){
    someDataA[i] = await func_a_as_promise(i);
  }

  // Second async loop that looks as sync one.
  for (j=0; j < num2; j++) {
    someDataB[j] = await func_b_as_promise(j);
  }

  // Do something with someDataA and someDataB here...
  // You'll get here after all async loops above are finished.
}
//依赖项。
const util=require('util');
//承诺你的职能。
const func_a_as_promise=util.promisify(func_a);
const func_b_as_promise=util.promisify(func_b);
//现在我们可以创建带有“wait”的“async”函数。
异步函数doSomething(){
//一些数据容器,如果您需要(?)。
常量someDataA=[];
常量someDataB=[];
//第一个看起来像同步循环的异步循环。
对于(i=0;i
这不允许循环的迭代并行完成。javascript中没有并行,但我明白你的意思。如果作者真的需要同时运行for循环,那么解决方案不能在Promises中包装
func\u a
func\u b
,而是整个for循环,然后使用相同的逻辑,或者
Promise.all
s/并行/并发
一般来说,如果代码不能在浏览器中直接运行,则不应在堆栈片段中。我已将其转换为代码块。这与问题相同。在每个单独调用上使用
wait
不允许循环中的异步函数工作按OP问题中的要求出租。
async function loop_a_b (num1, num2) {
  // await pauses execution until all asynchronous callbacks have been invoked
  const results_a = await Promise.all(
    loop_fn_n(func_a_promisified, num1)
  )

  const results_b = await Promise.all(
    loop_fn_n(func_b_promisified, num2)
  )

  return {
    a: results_a,
    b: results_b
  }
}
// Dependencies.
const util = require('util');

// Promisify your functions.
const func_a_as_promise = util.promisify(func_a);
const func_b_as_promise = util.promisify(func_b);

// Now we may create 'async' function with 'await's.
async function doSomething() {
  // Some data containers if you need any (?).
  const someDataA = [];
  const someDataB = [];

  // First async loop that looks like sync one.
  for (i=0; i < num1; i++){
    someDataA[i] = await func_a_as_promise(i);
  }

  // Second async loop that looks as sync one.
  for (j=0; j < num2; j++) {
    someDataB[j] = await func_b_as_promise(j);
  }

  // Do something with someDataA and someDataB here...
  // You'll get here after all async loops above are finished.
}