пустой массив вне вложенного обещания разрешения

1

im tring, чтобы нажать возвращаемое значение разрешения на переменную catWithItems которая находится за пределами разрешения. внутри разрешения catWithItems работает так, как ожидалось, но когда я catWithItems log 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. он делает вызов 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;
        });
}
  • 1
    Возможный дубликат Как я могу вернуть ответ от асинхронного вызова?
  • 0
    Просто предположение, что есть метод say .. foo() который прослушивает categoriesSearch(...).then((data) => res.json({categoryWithItems: data });) . Так что нет необходимости в res.json() в категорияхSearch ()
Теги:
foreach
promise
lodash

2 ответа

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
    да, я не справлялся с обещаниями правильно. ваш пример работы. благодарю вас
  • 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 });
}

Ещё вопросы

Сообщество Overcoder
Наверх
Меню