如何使用ES2016 async和nodejs分配值

时间:2018-04-30 21:42:05

标签: javascript promise

我正在编写node.js并表示在用户在地址栏上输入URL时构建API,他们将xmlhttpreq发送到另一个站点并发送值。现在这部分工作正常,但我想使用相同的信息进行进一步的编程。因此代码必须等待结果并将其分配给变量。所以我正在尝试等待和异步。以下是我的代码。

app.get('/super', function(req, res){
res.send(console.log(config.options()));
 // config is imported this where the async code is
});

Config.js

module.exports = {
    options : async () =>{
                let super  = await getGas();
                return super
            },
}
var getGas = async ()=>{
provider = ether.providers.getDefaultProvider();
provider.getGasPrice().then(//provider.getGas is a promise
    function(gasPrice) {
        gasPriceString = gasPrice.toString();
        return gasPriceString;
    },
    function(error){
        var errorObj = JSON.parse(error.responseText);
    }
);
}

我做错了什么?

1 个答案:

答案 0 :(得分:0)

如果您想使用async / await,请使用它来替换{​​{1}}:

then

当然整个事情仍然是异步的,所以在调用module.exports = { options: getGas, }; async function getGas() { const provider = ether.providers.getDefaultProvider(); try { const gasPrice = await provider.getGasPrice(); //provider.getGas() is a promise // ^^^^ const gasPriceString = gasPrice.toString(); return gasPriceString; } catch(error) { var errorObj = JSON.parse(error.responseText); throw errorObj; // what else would you do with it here? } } 函数时需要尊重它:

options