【问题标题】:Function return error "Cannot read property 'then' of undefined"函数返回错误“无法读取未定义的属性 'then'”
【发布时间】:2017-06-15 11:30:20
【问题描述】:

代码:

let parseCarList = [];

function addNewCars(req, res) {
    parseRequestAndCreateCarList(req.body)
        .then(function () {
            if (parseCarList.length != 0) {
                res.status(200).send('OK');
            }
        }, function (err) {
            res.status(200).send(err);
        });
}

function parseRequestAndCreateCarList(data) {
    return carListParsing(data);
}

function carListParsing(data, parentId = null) {
    //this function don't return anything
    //It parse req.body and fill the parseCarList array
    //I can't return anything because I use recursion
    parseCarList.push({
        car_company: data.car_company,
        parent_id: parentId
    });
    if (data.daughters) {
        data.daughters.forEach(item => {
            carListParsing(item, data.car_company);
        });
    }
}

我的函数carListParsing是做数组:

[ { car_company: 'vw', parent_id: null },
{ car_company: 'seat', parent_id: 'vw' }]

但我想确定,它的功能不会阻塞我的代码。

我收到错误“无法读取未定义的属性 'then'”。我的函数 parseRequestAndCreateCarList 是否返回已实现的承诺? 为什么在这种情况下“then”是未定义的?

附:有没有办法在没有包装器 parseRequestAndCreateCarList 的情况下离开 carListParsing?

【问题讨论】:

  • "这个函数不返回任何东西。它解析 req.body 并填充 parseCarList 数组。我不能返回任何东西,因为我使用递归"如果它不返回任何东西,你为什么期望它返回一个承诺?
  • 我的想法完全正确。您故意不返回任何内容,然后想知道为什么不能对不存在的结果调用函数?
  • 我不能返回任何东西,因为我使用递归”没有任何意义。尤其是在递归的情况下,你总是需要return一些东西。即使它只是递归调用的结果。
  • @Cruiser 我不知道如何将异步方法与不返回任何内容的函数一起使用。
  • 你在尝试使用承诺吗?您的 parseRequestAndCreateCarListcarListParsing 函数中没有任何异步内容!

标签: javascript promise


【解决方案1】:

你只能在返回的 Promise 上使用 then,所以你需要改变

function parseRequestAndCreateCarList(data) {
    return carListParsing(data);
}

function parseRequestAndCreateCarList(data) {
    return new Promise(function(resolve, reject) {
        resolve(carListParsing(data))
    });
}

【讨论】:

  • 不要。要么是同步的并且不需要使用 Promise,要么是异步的并且已经返回了 Promise。此外,这似乎不是 OPs 代码中的问题。
  • 如果你真的需要在promise中封装一些值,使用Promise.resolve(…)而不是promise构造函数。
猜你喜欢
  • 2021-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-13
  • 1970-01-01
  • 2017-04-21
相关资源
最近更新 更多