在Javascript中等待异步事件

时间:2017-07-10 13:46:57

标签: javascript node.js events asynchronous async-await

我是Javascript的新手,所以我需要帮助!

我有这个通讯文件:

var sDevices = {};
module.exports={
    initDevices: function(){
        client.findResources( )
        .catch( function( error ) {
            console.log( JSON.stringify( { assertion: "ok", arguments: [
                false, "Client: Starting device discovery failed: " +
                ( "" + error ) + "\n" + JSON.stringify( error, null, 4 )
            ] } ) );
        });
        client.on( "resourcefound",initThem);
    },
    getDevices:function(){
        return sDevices;
    }
}

与这个linstener:

async function initThem(resource){
   await client.retrieve(resource);
    if( _.has(resource,'properties.n') === true ){
        _.unset(resource,'properties.n');
    }
   sDevices[resource.resourceTypes[0]]=resource;
}

这是我的申请文件:

function start(){
    communication.initDevices();
    var devices=communication.getDevices();
    console.log(devices);
}

start();

所以问题是由于getDevices()的异步调用,应用程序js中的设备对象是空的。我可以用一些东西等待装满所有智能设备的sDevices吗?

0 个答案:

没有答案