search

Home  >  Q&A  >  body text

node.js - 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

是我的思路有问题吗?

迷茫迷茫2875 days ago354

reply all(3)I'll reply

  • 大家讲道理

    大家讲道理2017-04-17 15:29:47

    First of all, the return value of request is not Promise.
    Secondly, your getNode method does not return the result of request.

    You can change it like this:

    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)
                    })
                }
            })
        });
    }

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 15:29:47

    Correct answer upstairs, promise is used in the wrong place

    reply
    0
  • 怪我咯

    怪我咯2017-04-17 15:29:47

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

    Is there a Promise.map function? How to use it?

    reply
    0
  • Cancelreply