异步赋值获取值信息

https://www.runoob.com/w3cnote/javascript-promise-object.html

代码使用 then 方法,前一个函数返回的是Promise对象,这时后一个回调函数就会等待该Promise对象有了运行结果,才会进一步调用。

//获取实体名称的复数形式 
function GetEntityName() {
                var name = Xrm.Page.data.entity.getEntityName();//获取名称
                //拆分名称最后两个单词
                var last_two = name[name.length - 2];//t
                var last_one = name[name.length - 1];//y
                var last = last_two + last_one;//ty
                if (last_one == "y") {
                    last_one = "ies";
                }
                else if (last_one == "s" || last == "es") {
                    last_one = "ses";
                }
                else {
                    last_one = last_one + "s";
                }
                //截取除最后一位字母的部分
                name = name.substring(0, name.length - 1);
                //拼接复数单词
                name = name + last_one;
                return name;
            }
//异步赋值
function asyncGetValue() {
                return new Promise(
                    function (t_callback,f_callback) {
                        var entityId = Xrm.Page.data.entity.getId().replace('{', '').replace('}', '');
                        var url = Xrm.Page.context.getClientUrl() + "/api/data/v9.0/"+GetEntityName();
                        $.ajax({
                            url: url + "(" + entityId + ")",
                            type: "get",
                            async: true,//异步
                            contentType: "application/json;charset=utf-8",
                            success:(data)=>{
                                t_callback(data)
                            },error:(data)=>{
                                f_callback(false)
                            }
                        })
                    }
                )
            }
            var stuent_value = "";
            asyncGetValue().then((data)=> {
                stuent_value = data;
            }).catch((data)=>{
                stuent_value=data;
            });

如果前面函数返回的不是一个promise函数,那么直接将返回的值作为参数传递到then中写法如下

//promise传字符串
            function asyncGetValue() {
                return "字符串";
            }
            var student_value = "";
            Promise.resolve(asyncGetValue()).then((data)=> {
               student_value = data;
            }); 

原文地址:https://www.cnblogs.com/LanHai12/p/15257982.html