簡體   English   中英

在異步代碼的for循環完成后,如何解決此承諾?

[英]How do I resolve this promise after a for-loop of asynchronous code finishes?

似乎無法弄清楚如何在沒有setTimeout的情況下進行這項工作。 我只想在異步PostgreSQL內容完成並且該映射包含它應該包含的所有鍵/值對之后,控制台記錄我的映射。

const map = new Map();
pool.query(`SELECT * FROM trips WHERE destination = $1 AND begin_time >= $2 AND begin_time < $3 ORDER BY begin_time`, ['BROWNSVILLE ROCKAWAY AV', '2018-07-18 00:00-04:00', '2018-07-19 00:00-04:00'])
.then(res => {
    return new Promise((resolve, reject) => {
        const { rows } = res;
        resolve(rows);
    });
})
.then(res1 => {
    return new Promise((resolve, reject) => {
        for (let i = 0; i < res1.length; i++) {
            if (res1[i + 1]) {
                pool.query(`SELECT * FROM get_hwtable($1, $2)`, [res1[i].trip_id, res1[i + 1].trip_id]).then(res => {
                    const { rows: hwRows } = res;
                    map.set([res1[i].trip_id, res1[i + 1].trip_id], hwRows);
                }).catch(e => console.log('20', e));
            }
        }
        setTimeout(() => {
            resolve(map);
        }, 8000);
    });
})
.catch(e => console.log('25', e))
.finally(function () {
    console.log(map);
});

你可以簡單地使用Promise.all由歸國承諾陣列上pool.query

const map = new Map();
pool.query(`SELECT * FROM trips WHERE destination = $1 AND begin_time >= $2 AND begin_time < $3 ORDER BY begin_time`, ['BROWNSVILLE ROCKAWAY AV', '2018-07-18 00:00-04:00', '2018-07-19 00:00-04:00'])
.then(({rows}) => rows)
.then(res1 => Promise.all(res1.map((r, i) => {
    if (res1[i + 1]) {
        return pool.query(`SELECT * FROM get_hwtable($1, $2)`, [r.trip_id, res1[i + 1].trip_id])
        .then(res => {
            const { rows: hwRows } = res;
            map.set([res1[i].trip_id, res1[i + 1].trip_id], hwRows);
        }).catch(e => console.log('20', e))
    }                                 
})))
.catch(e => console.log('25', e))
.finally(function () {
    console.log(map);
});
  1. 您的代碼中有不必要的構造。 首先then( res => {..} ) ,不需要返回Promise 你可以做

```

pool.query().then(res => {
    const {rows} = res;
    return rows;
}.then ....

```

  1. 如果已經在使用async ,則應該使用await並將其用於整個代碼塊。 也可以編寫一個承諾的超時函數。

```

///returns a promise that resolves after `duration`
function timeoutPromise(duration) {
  return new Promise((resolve, reject) => {
    setTimeout(resolve, duration)
  })
}

async function doSomething() {
  const res = await pool.query()
  const {rows} = res;
  for (...) {
    let hwRows = await pool.query(`SELECT * FROM get_hwtable($1, $2)`, [res1[i].trip_id, res1[i + 1].trip_id]);
    map...
  }
  await timeoutPromise(5000)
}

doSomething()

```

  1. 當然,以上內容可能會使用戶等待太久,因為異步操作( let hwRows = await pool.query() )將一次又一次地執行。 使用Array.map返回Promise數組,然后使用Promise.all([Promise])獲取值。

```

async function doSomething() {
  const res = await pool.query()
  const {rows} = res;
  let hwRowsPromises = rows.map((row) => {
    // ...
    // return the promise
    return pool.query(`SELECT * FROM get_hwtable($1, $2)`, [res1[i].trip_id, res1[i + 1].trip_id])
  })
  let hwRowsResults = Promise.all(hwRowsPromises)
  await timeoutPromise(5000)
}

```4. Promise.all解析數組中由Promise.all解析的值,因此您可以使用諸如flattenPromise.all數組的便利。

```

_.flatten([1, [2, [3, [4]], 5]]);
// => [1, 2, [3, [4]], 5]

```

參考文獻

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM