node Promise的问题

function getNode(subjectId, nodeId){
    
    request(`http://hr.amiaodaifu.com:50000/1610/questions/${subjectId}/get-children/${nodeId}`, (err, res, body) => {
        console.log(body)
        if(err){
            return console.log("err: ",err)
        } else {
            const content = JSON.parse(body); 
            console.log(content)
            return content.length == 0 ? Promise.resolve(content) : Promise.resolve({
                id: nodeId,
                children: JSON.parse(body)
            })
        }
    })
}

function getTree(subjectId, nodeId){

    getNode(subjectId, nodeId)
        .then(items => {
            return Promise.map(items.children, item => (getTree(item)))
        })
        // .then((children) => ({
        //     id: nodeId,
        //     children
        // }))
}

调用getTree的时候,提示的错误是:

Cannot read property 'then' of undefined

是我的思路有问题吗?

阅读 2.3k
3 个回答

首先,request返回值不是Promise
其次,你的getNode方法里也没有返回request的结果。

可以这么改下:

function getNode(subjectId, nodeId){
    
    return new Promise((resolve, reject) => {
            request(`http://hr.amiaodaifu.com:50000/1610/questions/${subjectId}/get-children/${nodeId}`, (err, res, body) => {
            if(err){
                return reject("err: ",err)
            } else {
                const content = JSON.parse(body); 
                return content.length == 0 ? resolve(content) : resolve({
                    id: nodeId,
                    children: JSON.parse(body)
                })
            }
        })
    });
}

楼上正解, promise用错地方了

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题