如何在Promise'd函数中调用助手函数

时间:2019-02-06 15:27:22

标签: javascript promise helper

我对Javascript还是陌生的,我希望那里的人可以帮助我解决一个问题,就是我只是无法缠住我的头!!

我有一个函数,其中包含很多重复的代码,因此尝试将其分解为一个辅助函数。但是,当我从lMS函数(当前称为lMS(f).then()中调用helper函数时,helper函数将在init(g)函数之后执行,这取决于lMS首先执行并完成。 >

由于对Promise的工作方式和异步函数的性质的误解,我有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

更新

“ {help}函数”代码中包含了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);
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

经过数天的尝试和大量研究,我确定了如何做到这一点。

使用//post new item axios.post('/items.json', itemData) etc.... //get all items axios.get('/items.json') .then(res => { const fetchedItems = []; for (let key in res.data) { fetchedItems.push({ ...res.data[key], }); } etc.... //sort all items like this: fetchedItems.sort(function (a, b) { return new Date(b.date) - new Date(a.date); }); //replace "items" with "fetchedItems" on Firebase somehow... 遍历数组值(而不是尝试Array.forEach循环)意味着我可以将每个promise推送到数组,然后在数组上for! :)

Promise.all

我可以确认它现在正在按预期运行! https://codepen.io/willstocks_tech/pen/YBEzLW?editors=1012

我已经对Promises /异步代码的执行有了更多的了解:)感谢@Bergin提供的所有帮助