嵌套解析承诺之外的空数组

时间:2018-10-17 18:21:54

标签: javascript node.js foreach promise lodash

正在尝试将解析的返回值推送到解析之外的变量catWithItems。在解决方案内部,catWithItems可以按预期工作,但是当我在循环外控制台catWithItems控制台时,它将返回一个空数组。

function categoriesSearch(req, res, next) {
    let categories = req.batch_categories;
    let catWithItems = [];
    _.forEach(categories, (category) => {
        return new Promise(resolve => {
            pos.categoriesSearch(req.tenant, category.id)
            .then(item => {
                if(item) category.items = item[0];
                return category;
            })
            .then(category => {
                catWithItems.push(category);
                console.log(catWithItems); //this is works inside here
                return resolve(catWithItems);
            });
        });
    });
    console.log(catWithItems); //doesn't work returns empty array
    res.json({categoryWithItems: catWithItems });
}

这是pos.categoriesSearch模块。它对Square进行了api调用。(这可以正常工作)

function categoriesSearch(tenant, category) {
    let search_items_url = ${tenant.square.api.v2}/catalog/search,
        apiKey = tenant.square.api.key,
        payload = {
            "object_types": ["ITEM"],
            "query": {
                "prefix_query": {
                    "attribute_name": "category_id",
                    "attribute_prefix": category
                }
            },
            "search_max_page_limit": 1
        },
        conf = config(search_items_url, apiKey, payload);
        return request.postAsync(conf)
        .then(items => {
            return items.body.objects;
        });
}

2 个答案:

答案 0 :(得分:1)

您不履行承诺是正确的。尝试这种方式。

function categoriesSearch(req, res, next) {
    let categories = req.batch_categories;
    let promiseArray = []; // create an array to throw your promises in
    let catWithItems = [];
    categories.map((category) => {
        let promise = new Promise(resolve => {
            pos.categoriesSearch(req.tenant, category.id)
            .then(item => {
                if(item) category.items = item[0];
                return category;
            })
            .then(category => {
                catWithItems.push(category);
                console.log(catWithItems); //this is works inside here
                return resolve(catWithItems);
            });
        });
        promiseArray.push(promise) // add promises to array
    });
    // resolve all promises in parallel
    Promise.all(promiseArray).then((resolved) => {
       console.log(resolved);
       res.json({categoryWithItems: catWithItems });
    })
}

答案 1 :(得分:0)

应该容易得多。不确定是否可行,但可以从以下内容开始:

function categoriesSearch(req, res) {
    const categoryWithItems$ = req.batch_categories.map(category =>
        pos.categoriesSearch(req.tenant, category.id)
            .then(item => ({ ...category, items: item[0] })
    );

    Promise.all(categoryWithItems$)
        .then(categoryWithItems => res.json({ categoryWithItems });
}