如何调用Promise'd函数内的辅助函数

问题描述 投票:0回答:1

我还是新的Javascript和我希望有人在那里可以帮助我,我有,我只是一直没能绕到我的脑袋有问题!

我有很多在这重复的代码的函数,因此试图分拆其关闭到一个辅助功能。然而,当我打电话从LMS功能(当前正被称为lMS(f).then()内的辅助功能,辅助功能执行init(g)函数,它是上执行和第一完成LMS依赖AFTER。

我99%肯定我有这个问题,由于我如何Promises工作和异步函数性质的误解。

我曾尝试推动重复的代码放到一个单独的函数并调用在需要时。我已经尝试捕获的,所述响应作为承诺,或推动响应转换成一个数组,然后仅当我有所有项目返回(相比于原始阵列)中执行的。

以下是原始脚本,在没有辅助功能,但重复的代码块好:https://github.com/willstocks-tech/dynamically-polyfill-features-for-a-script/releases/tag/0.0.5b5 - 57行(function loadMyScript(url)

我已经把助手代码为Codepen(我已经工作了数天)https://codepen.io/willstocks_tech/pen/pGgRrG?editors=1012

更新

内“辅助函数”的代码和一个新的笔所有的细节,我已经尝试了包括init功能/我目前正在根据反馈:https://codepen.io/willstocks_tech/pen/YBEzLW?editors=1012

当前的代码:

function lMS(f) {
    if(Array.isArray(f)) {
        var urlen = f.length;
        for (var u = 0; u < urlen; u++) {
            var uri = f[u];
            if(uri !== null && uri !== '') {
                return new Promise(
                    function(resolve, reject) {
                        var thescript = document.createElement('script');
                        thescript.src = encodeURI(uri);
                        document.body.appendChild(thescript);
                        thescript.onerror = function(response) {
                            return reject("Loading the script failed!", response);
                        } 
                        thescript.onload = function() {
                            return resolve("Script setup and ready to load!");
                        } 
                    }
                )
            } else {
                return new Promise( //pretty sure this could just be Promise.resolve();
                    function(resolve, reject) {
                        return resolve ("No script to load");
                    }
                )
            }
        }
    } else {
        if(f !== null && f !== '') {
            return new Promise(
                function(resolve, reject) {
                    var thescript = document.createElement('script');
                    thescript.src = encodeURI(f);
                    document.body.appendChild(thescript);
                    thescript.onerror = function(response) {
                        return reject("Loading the script failed!", response);
                    } 
                    thescript.onload = function() {
                        return resolve("Script setup and ready to load!");
                    } 
                }
            )
        } else {
            return new Promise( //pretty sure this could just be Promise.resolve();
                function(resolve, reject) {
                    return resolve ("No script to load");
                }
            )
        }
    }
}

在(与助手)的进展新作:

function pL(e, f, g) {
    cNS(e).then(
        function() {
            lMS(f, g)
        }
    ).catch(function(error){return error})
    }
}

function lMS(f, g) {
    var w = [];
    if(Array.isArray(f)) {
        var urlen = f.length;
        for (var u = 0; u < urlen; u++) {
            var uri = f[u];
            if(uri !== null && uri !== '') {
                uriProm(uri); //go and get a script that is needed
                w.push(uri);  //maybe push to array and return resolve once everything is done?
            } else {
                return;
            }
        }
        if(w.length === url.length && w.every(function(value, index) { return value === url[index]})) {
            console.log("We've made it to here");
            return init(g) //go off to run a piece of code based reliant on the script of uriProm
            }
    } else { //not an array of values
        if(url !== null && url !== '') {
            uriProm(uri);
            return init(g)
        } else {
            return
        }
    }
}

//helper function (avoiding duplicate code)
function uriProm(uri){
    var thescript = document.createElement('script');
    thescript.src = encodeURI(uri);
    document.body.appendChild(thescript);
    thescript.onerror = function(response) {
        return reject("Loading the script failed!", response);
    } 
    thescript.onload = function() {
        return Promise.resolve();
    } 
}

    function init(g) {
        if(Array.isArray(g)) {
            var fnlen = g.length;
            for (var f = 0; f < fnlen; f++) {
                try {
                    new Function(g[f])();
                } catch(err) {
                    console.error('There was an error: ', err.name, err.stack);
                }
            }           
        } else {    
            try {
                new Function(g)();
            } catch(err) {
                console.error('There was an error: ', err.name, err.stack);
            }
        }
    }
javascript promise helper
1个回答
0
投票

经过尝试和研究吨天,我制定了我怎么能做到这一点。

使用Array.forEach通过数组值进行迭代(而不是试图for环)意味着我可以每个承诺推到一个数组,然后Promise.all阵列上! :)

//This won't run in JSFiddle because the rest of the function doesn't exist
//https://github.com/willstocks-tech/dynamically-polyfill-features-for-a-script/releases - 0.0.5-beta.6

function lMS(f, g) {
  if (Array.isArray(f)) { //Check whether array is being passed or just string
    var promises = []; //Gotta catch 'em all... as an array
    f.forEach( //iterate through the array using Array.forEach()
      function(f) { //pass each item in the array through to the "get script" function
        promises.push(nbU(f)) //push the resolve/reject into the promises array
      }
    );
    Promise.all(promises) //Make sure that all promises that are returned come back as resolved
      .then( //then
        () => init(g) //run the init function!
      );
  } else if (!Array.isArray(f) && f !== null && f !== '') { //if not an array and not blank values
    return nonblankURL(f) //resolve or reject getting the script
      .then( //then
        () => init(g) //run the init function!
      )
  } else { //not array, blank values
    return init(g); //straight to init because no dependency (blank)
  }
}

我可以证实,这是工作作为目前预计! https://codepen.io/willstocks_tech/pen/YBEzLW?editors=1012

我已经长大了明白的承诺/异步代码执行多一点:)谢谢@Bergin所有援助

© www.soinside.com 2019 - 2024. All rights reserved.