node.js - Promise 取值问题
巴扎黑
巴扎黑 2017-04-17 16:24:23
0
2
699

问题描述:

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

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

巴扎黑
巴扎黑

reply all(2)
迷茫

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

黄舟

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);
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template