如何等待承诺解决?

时间:2015-07-19 11:11:17

标签: angularjs promise

我需要等待承诺解决。

    public class PlayerListener implements Listener {

    public PlayerListener(Main plugin) {
        plugin.getServer().getPluginManager().registerEvents(this, plugin);
    }

    // public static final String bannedBlocksString = "DIAMOND_BLOCK; EMERALD_BLOCK";

    public static final String[] bannedBlocks = bannedBlocksString.split("; ");

    public static boolean isBannedBlock(String[] bannedBlocks, String blockPlaced) {
        boolean returnValue = false;
        for (String bannedBlock : bannedBlocks) {
            if(blockPlaced.equalsIgnoreCase(bannedBlock)){
                returnValue = true;
            }
        }
        return returnValue;
    }

    @EventHandler
    public void onBlockPlace(BlockPlaceEvent event) {

        String blockPlaced = event.getBlockPlaced().getType().toString();

        if(!event.getPlayer().hasPermission("antibuild.block.noplace") && isBannedBlock(bannedBlocks, blockPlaced)) {
            event.setCancelled(true);
            event.getPlayer().sendMessage(ChatColor.RED + "You can not place this block.");
        }

    }

}

更新

我试着澄清我的问题。 我有带有返回promise的函数的myService服务:

 function myFunction(myService, projectId) {
        var localdata;
        var myDataPromise = myService.getData(projectId);
        myDataPromise.then(function(result) {  
           localdata = result;
        });
        var someResult = someProcess(localdata); // I need to wait for promise resolution.
        return someResult;
    }

2 个答案:

答案 0 :(得分:1)

您不需要本地变量 ...

function myFunction(myService) {
    return myService.getData().then(function(result) {  
       return result;
    });
}

你的来电者将是:

myFunction(myService).then(function(result){
    //you can be sure that result is fully computed here
    console.log("Your result " + result);
}) 

答案 1 :(得分:0)

想要从承诺中返回数据! 你想要返回一个承诺,以“继续”链。

您正在寻找的等待是您附加到承诺的回调。

function myFunction($scope, myService) {
    var myDataPromise = myService.getData();

    myDataPromise.then(function(result) {  
       // this is the "wait" your looking for.. 
       $scope.data = result;
       console.log("data.name"+$scope.data.name);
    });

    return myDataPromise; // return the promise
}