node.js - node Promise的问题
迷茫
迷茫 2017-04-17 15:27:47
0
3
367
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

是我的思路有问题吗?

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

모든 응답(3)
大家讲道理

우선 request의 반환값은 Promise이 아닙니다.
두 번째로, getNode 메소드는 request의 결과를 반환하지 않습니다.

다음과 같이 변경할 수 있습니다.

으아악
Ty80

위층은 정답인데 약속이 엉뚱한 곳에서 쓰였습니다

刘奇

Promise.map(items.children, item => (getTree(item))) 반환

Promise.map 기능이 있나요? 어떻게 사용하나요?

최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿