search

Home  >  Q&A  >  body text

node.js - JS的异步问题


如图想在reqst函数内部返回body的内容,求指教~

黄舟黄舟2785 days ago437

reply all(3)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 15:34:07

    callback

    reply
    0
  • 怪我咯

    怪我咯2017-04-17 15:34:07

    (err,res,body)=>{} is a callback, right?
    It should be written like this

    (err,res)=>{
            if(err){
            throw err
            }else{
            return (
            //对res进行操作
            )
            }
        }

    res should be the data returned by the background. I don’t know the format, so I can only write an idea.

    reply
    0
  • 高洛峰

    高洛峰2017-04-17 15:34:07

    // callback
    function rqst(callback) {
        request({}, (err, res, body) => {
            if (err) return callback(err);
            callback(null, body);
        })
    }
    
    rqst(function(err, body) {
        // body
    })
    
    // promise
    function rqst() {
        return new Promise(resolve, reject) => {
            request({}, (err, res, body) => {
                if (err) reject(err);
                resolve(body)
            })
        }
    }
    
    rqst.then(body => {
        // body
    }).catch(e => {
    })

    reply
    0
  • Cancelreply