与承诺中的循环同步

时间:2018-03-01 13:53:49

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

最近我搞砸了承诺。我想在extractMovie()中实现的是遍历所有给定的URL,解析它们,得到一些日期,将它存储在一个数组中并解析该数组。但实际发生的是解析result(这是一个空数组),然后循环遍历网址。实际上,一个空数组正在被解析为parallel()函数。关于如何在承诺中实现同步性的任何想法?

const extractMovie = (movieUrl) => {
    return new Promise((resolve, reject) => {
        const fullUrl = mainDomain + movieUrl;
        domParser(fullUrl).then(($) => {
            const titleSelector = '.title h2';
            const ratingSelector = '.user_score_chart';
            const runtimeSelector = '.facts p:nth-child(9)';

            const obj = {
                title: $(titleSelector).html(),
                rating: $(ratingSelector).attr('data-percent'),
                runtime: $(runtimeSelector).text(),
            };
            resolve(obj);
        });
    });
};

const arrayProcessing = async (array) => {
    const results = [];
    for (const entry of array) {
        results.push(await extractMovie(entry));
    }
    return results;
};

const parallel = async (movieUrl1, movieUrl2) => {
    const task1 = arrayProcessing(movieUrl1);
    const task2 = arrayProcessing(movieUrl2);

    return {
        res1: await task1,
        res2: await task2,
    };
};

const run = async () => {
    try {
        const urls = await goInPage();
        await parallel(urls.page1, urls.page2).then((result) => {
            console.log(result);
        });
    } catch (err) {
        console.log(err);
    }
};

run();

0 个答案:

没有答案
相关问题