search

Home  >  Q&A  >  body text

node.js - Promise 取值问题

问题描述:

var promise = client.getMap(config.map);
promise.then(function (rs) {
    console.log(rs);
});

这个promise是个Promise的对象,里面包裹了我想要的值rs,但是貌似只能通过promise.then这种方式异步方式取值,我想定义一个变量去接收,然后在继续往下做。新手对promise还不是很熟

巴扎黑巴扎黑2788 days ago701

reply all(2)I'll reply

  • 迷茫

    迷茫2017-04-17 16:26:23

    If you want to use promise, you have to use then/catch, or use async/await to directly convert asynchronous operations into synchronous operations.

    async function getRS (){
        try{
            let rs = await client.getMap(config.map);
            console.log(rs);
            return rs;
        } catch(err){
            console.error(err);
        }
    }
    
    getRS();
    

    async/await learning reference teacher Ruan Yifeng => http://es6.ruanyifeng.com/#do...

    soonfy

    reply
    0
  • 黄舟

    黄舟2017-04-17 16:26:23

    If you are not familiar with promises, don’t bother with ES6’s async/await, you will be even more confused.
    If you are not familiar with promises, you can just use then as a callback (actually promises are quite easy to learn)

    var value;
    function cb(rs){
        value = rs;
        console.log(value);
    }
    function onerr(err){
        console.error(err);
    }
    client.getMap(config.map).then(cb,onerr);

    reply
    0
  • Cancelreply