Цикл внутри асинхронного / ожидания в NodeJS - PullRequest
0 голосов
/ 18 января 2020

С Async / Await как мне l oop более MOVIES (массив строк), чтобы я мог сделать вызов search() один раз для каждого элемента, сохранить полученный объект и в итоге получить массив с именем TORRENTS?

const TorrentSearchApi = require('torrent-search-api');
const fs = require('fs');

const DATA = fs.readFileSync('./movies.json');
const MOVIES = JSON.parse(DATA);

TorrentSearchApi.enableProvider('1337x');

(async () => {
  let array = [];
  let torrent;

  async function search() {
    try {
      // Here: How do I loop over 'MOVIES' so I can the interpolate that value as `${movie}` and push the result to array?
      torrent = await TorrentSearchApi.search(`${movie} 1080`, 'Movies', 1);
    } catch (e) {
      console.error(e);
    }

    return array;
  }
  // for each 'movie' in 'MOVIES' there should be one item in the 'TORRENTS' array now
  const TORRENTS = await search();
})();

Ответы [ 2 ]

2 голосов
/ 18 января 2020

Вы можете использовать Array.prototype.map() на MOVIES и отображать каждое движение ie string на ожидаемое Promise, затем await на Promise.all() для продолжения после разрешения всех Promise с и у тебя есть все свои торренты.

(async () => {
  async function search() {
    try {
      // return value will be a Promise
      return await TorrentSearchApi.search(`${movie} 1080`, 'Movies', 1);
    } catch (e) {
      console.error(e);
      // we're not returning anything in case of an error, so the return value will be `undefined`
    }
  }

  const TORRENTS = await Promise.all(
    MOVIES
      .map((movie) => search(movie))
      .filter((torrentPromise) => torrentPromise !== undefined) // here we filter out all the searches that resulted in an error
  );
})();
0 голосов
/ 18 января 2020

Предполагая, что MOVIES является <array>, а ${movie} является <string | number> значением:

try {
  MOVIES.map(async movie => {
   torrent = await TorrentSearchApi.search(`${movie} 1080`, 'Movies', 1);
   array.push(torrent);
  });
} catch (e) {
  console.error(e);
}
...