等待Promise.all没有生效

时间:2018-05-17 12:00:51

标签: javascript node.js promise async-await es6-promise

下面是我的 async 函数,用于从DB读取值并在控制台上记录一些内容。但由于某种原因,它没有发生。

因此,我创建了一个promises数组,然后等待所有承诺解析,因为promises将从DB中读取。但是等待 Promise.all 上没有暂停代码的执行而不是等待所有的promises解决,而是将其控制权传递回调用函数。 这里有什么我想念的吗?

async function readValuesFromDB(codes) {
  console.log('trying to read values from DB');
  let dbPromises = [];
  for(let code in codes) {
    let refId = 'some_random_reference_id_generated_from_codes[i]';
    dbPromises.push(MyDb.getPromise(refId)); // getPromise() returns a promise that reads from DB
  }
  console.log('waiting for all promises to resolve...');

  // waiting for all promises to finish 
  await Promise.all(dbPromises).then((allPromises) => {
    for(let i in allPromises) {
      console.log('OK..read from DB');
    }
  });
  console.log('all promises resolved');

}

console.log('calling readValuesFromDB()');
readValuesFromDB();
console.log('finished readValuesFromDB()');

以上来电的输出是:

trying to read values from DB
waiting for all promises to resolve...
finished readValuesFromDB
......
......
OK..read from DB
OK..read from DB
OK..read from DB
...
...
all promises resolved

理想情况下输出应低于(因为我等待所有使用 await 解决所有承诺 Promise.all

trying to read values from DB
waiting for all promises to resolve...
OK..read from DB
OK..read from DB
OK..read from DB
...
...

所以看起来在将控件传递回调用函数之后,promises会得到解决,并且似乎 await 在这里没有效果。

在这种情况下等待的原因没有任何帮助吗?

3 个答案:

答案 0 :(得分:3)

行为正常。

import numpy as np def method_orig(a, m): b_row = -np.ones((m, 2), dtype=int) b_col = -np.ones((m, 2), dtype=int) count = np.zeros(m, dtype=int) for k, row in enumerate(a): i = count[row] b_row[row, i] = k b_col[row, i] = [0, 1, 2] count[row] += 1 return b_row, b_col def method_jdehesa(a, m): a_flat = a.flatten() # Or a.ravel() if can modify original array v1, idx1 = np.unique(a_flat, return_index=True) a_flat[idx1] = -1 v2, idx2 = np.unique(a_flat, return_index=True) v2, idx2 = v2[1:], idx2[1:] rows1, cols1 = np.unravel_index(idx1, a.shape) rows2, cols2 = np.unravel_index(idx2, a.shape) b_row = -np.ones((m, 2), dtype=int) b_col = -np.ones((m, 2), dtype=int) b_row[v1, 0] = rows1 b_col[v1, 0] = cols1 b_row[v2, 1] = rows2 b_col[v2, 1] = cols2 return b_row, b_col n = 100000 c = 3 m = 200000 # Generate random input # This does not respect "no doubled indices in row" but is good enough for testing np.random.seed(100) a = np.random.permutation(np.concatenate([np.arange(m), np.arange(m)]))[:(n * c)].reshape((n, c)) %timeit method_orig(a, m) # 3.22 s ± 1.3 s per loop (mean ± std. dev. of 7 runs, 1 loop each) %timeit method_jdehesa(a, m) # 108 ms ± 764 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) 运行异步,而不是readValuesFromDB

因此,在readValuesFrom DB解析之前,控制台正在解析“已完成”。

你可以这样做:

console.log('finished readValuesFromDB()');

或者像这样:

async function readValuesFromDB(codes) {
      console.log('trying to read values from DB');
      let dbPromises = [];
      for(let code in codes) {
        let refId = 'some_random_reference_id_generated_from_codes[i]';
        dbPromises.push(MyDb.getPromise(refId)); // getPromise() returns a promise that reads from DB
      }
      console.log('waiting for all promises to resolve...');
    
      // waiting for all promises to finish 
      let allPromises = await Promise.all(dbPromises);
  for(let i in allPromises) {
    console.log('OK..read from DB');          
  }  
  console.log('all promises resolved');
      console.log('finished readValuesFromDB()');
    }
    
    console.log('calling readValuesFromDB()');
    readValuesFromDB();

答案 1 :(得分:1)

你错过了等待:

(async function() {
  console.log('calling readValuesFromDB()');
  await readValuesFromDB();
  console.log('finished readValuesFromDB()');
})();

答案 2 :(得分:-1)

您必须await拨打readValuesFromDB

console.log('calling readValuesFromDB()');
await readValuesFromDB();
console.log('finished readValuesFromDB()');