带有返回数据的 JS 异步队列

问题描述 投票:0回答:0

我想向 google api 发出异步请求并将结果保存在一个数组中。我试图以某种方式从 apiHandler 返回值的尝试失败了。你能帮帮我吗?

我对js不是很有经验,更不用说异步js了。

import { queue } from "async";
import fetch from "node-fetch";

let concurrency = 10; // How many async processes will be running
let KEY = '';
let ids = [
    'sMTs5bvAsGA',
    'kW5X4dU0gnY',
    'dX2hyyKFIHA',
    '91egEkKuVas',
    'DfhKbYXRu6Q',
    'hQdOqC-1tVg',
    'AOwFmabnb7s',
];

let data = [];

export const taskQueue = queue(async (task, done) => {
    try {
        await task();
        done;
    } catch (err) {
        throw err;
    }
}, concurrency);

taskQueue.drain(() => {
    console.log("All items completed!\n");
    process.exit();
});

export function getItems(video_ids) {
    video_ids.forEach((id) => {
        taskQueue.push(() =>
            apiHandler(`https://www.googleapis.com/youtube/v3/search?part=snippet&relatedToVideo=${id}&maxResults=50&type=video&key=${KEY}`), 
            
            (err) => {
                if (err) {
                    console.log(err);
                    throw new Error('Error getting data.');
                }
            })
    });
};

async function apiHandler(url) {
    const response = await fetch(url);
    const data = await response.json();
    console.log(data);
}

getItems(ids);
javascript node.js asynchronous google-api queue
© www.soinside.com 2019 - 2024. All rights reserved.