在Javascript中等待异步事件

在Javascript中等待异步事件,javascript,node.js,events,asynchronous,async-await,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: [

我是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();

因此,问题是应用程序js中的devices对象是空的,因为异步调用了getDevices()。我可以使用一些东西来等待所有智能设备的数据设备吗?

学习使用Promise这里有实际的代码来填充
数据设备的值
?您不能在Javascript中“等待”异步操作。相反,您设置了一个回调或承诺,当异步操作完成并且您在该回调中执行工作时,该回调或承诺将通知您。要在sDevices中存储值,我使用侦听器,代码如下:sDevices[resource.resourceTypes[0]]=resource@jfriend00 with
wait
他可以“wait”这是承诺解决方案的语法糖。在您的
start
函数中,您没有等待任何东西。另外,您什么时候知道
findResources
已经找到了所有资源(并触发了所有要等待的
resourcefound
事件)?