[axios][问题]如何运行axios.post循环?

2024-08-22 316 views
7

我有一个遍历数组的 for 循环,其中每个索引中我都必须有一个 axios.post 请求来创建某些文件。但看起来它会自动跳过所有 axios.post 请求,只执行数组的最后一个索引。{奇怪}

for (let i = 0; i < rawConfigs[1].pageSettings.length; i++) {
    var partials = '';
    console.log("i:", i)
    var nameF = rawConfigs[1].pageSettings[i].PageName.split('.')[0]
    console.log("page name:", nameF)
    let responseConfig = await axios.get(this.baseURL + '/flows-dir-listing/0?path=' + this.$store.state.fileUrl + '/assets/config.json');

    console.log("response:", JSON.parse(responseConfig.data))
    let rawSettings = JSON.parse(responseConfig.data);

    var Layout, partialsPage = '';
    Layout = rawConfigs[1].pageSettings[i].PageLayout
    partialsPage = rawConfigs[1].pageSettings[i].partials
    var responseMetal = ''
    console.log("value of responseMetal:", responseMetal)
    responseMetal = "var Metalsmith=require('metalsmith');\nvar markdown=require('metalsmith-markdown');\nvar layouts=require('metalsmith-layouts');\nvar permalinks=require('metalsmith-permalinks');\nvar fs=require('fs');\nvar Handlebars=require('handlebars');\n Metalsmith(__dirname)\n.metadata({\ntitle: \"Demo Title\",\ndescription: \"Some Description\",\ngenerator: \"Metalsmith\",\nurl: \"http://www.metalsmith.io/\"})\n.source('')\n.destination('" + folderUrl + "/MetalsmithOutput')\n.clean(false)\n.use(markdown())\n.use(layouts({engine:'handlebars',directory:'" + folderUrl + "/Layout'}))\n.build(function(err,files)\n{if(err){\nconsole.log(err)\n}});"

    var index = responseMetal.search('.source')

    responseMetal = responseMetal.substr(0, index + 9) + this.$store.state.fileUrl + '/Preview' + responseMetal.substr(index + 9)
    var indexPartial = responseMetal.search("('handlebars')");
    for (var x = 0; x < partialsPage.length; x++) {
        let key = Object.keys(partialsPage[x])[0];
        console.log("key :", key)
        let value = partialsPage[x]
        let key2 = key;
        console.log("value:", value[key2])
        key = key.trim();
        if (value[key2].match('html')) {
            console.log("inside html if")
            key = key.split('.')[0]
            var temp = "Handlebars.registerPartial('" + key + "', fs.readFileSync('" + folderUrl + "/" + key + "/" + value[key2] + "').toString())\n"
        } else if (value[key2].match('hbs')) {
            console.log("inside hbs if")
            key = key.split('.')[0]
            var temp = "Handlebars.registerPartial('" + key + "', fs.readFileSync('" + folderUrl + "/" + key + "/" + value[key2] + "').toString())\n"
        } else {
            console.log("inside else")
            var temp = "Handlebars.registerPartial('" + key + "', fs.readFileSync('" + folderUrl + "/" + key + "/" + value[key2] + ".html').toString())\n"
        }

        partials = partials + temp;

    }
    console.log("partials of metalsmith:", partials);

    responseMetal = responseMetal.substr(0, indexPartial + 15) + partials + responseMetal.substr(indexPartial + 15);

    let mainMetal = folderUrl + '/assets/metalsmith.js'
    console.log("final metalsmith file ready for api call:", responseMetal);
    console.log("@@@@@@@@@@@@@@@@@:")
    console.log("mainMetal:", mainMetal)
    // IT WILL EXECUTE TILL HERE AND AUTOMATICALLY SKIP THIS PORTION OF AXIOS AND START FROM CONSOLE i .i.e above.

    axios.post('http://localhost:3030/flows-dir-listing', {
            filename: mainMetal,
            text: responseMetal,
            type: 'file'
        }).then((response) => {
            this.$message({
                showClose: true,
                message: 'MetalSmith Config Saved!',
                type: 'success'
            });

            var newFolderName = folderUrl + '/Preview';
            axios.post(this.baseURL + '/flows-dir-listing', {
                    foldername: newFolderName,
                    type: 'folder'
                })
                .then(async(res) => {
                    console.log(res)

                    var newContent = await axios.get(this.baseURL + '/flows-dir-listing/0?path=' + this.$store.state.fileUrl + '/Pages/' + nameF + '.html');

                    newContent = newContent.data;

                    if (Layout == 'Blank') {
                        if (newContent.match('---')) {
                            let substr = newContent.substr(newContent.search('---'), newContent.search('<'))
                            console.log("substr:" + substr)
                            newContent = newContent.replace(substr, '')
                        } else {
                            newContent = newContent
                        }

                    } else {
                        let tempValueLayout = '---\nlayout: ' + Layout + '.layout\n---\n';

                        console.log("tempValueLayout:" + tempValueLayout)

                        if (newContent.match('---')) {
                            let substr = newContent.substr(newContent.search('---'), newContent.search('<'))
                            console.log("substr:" + substr)
                            newContent = newContent.replace(substr, tempValueLayout)
                        } else {
                            newContent = tempValueLayout + newContent
                        }

                    }
                    let previewFileName = folderUrl + '/Preview/' + nameF + '.html';

                    axios.post('http://localhost:3030/flows-dir-listing', {
                            filename: previewFileName,
                            text: newContent,
                            type: 'file'
                        })
                        .then((res) => {
                            this.saveFileLoading = false;

                            axios.get('http://localhost:3030/metalsmith?path=' + folderUrl, {}).then((response) => {
                                    console.log('successfully  :' + (response))

                                    var metalsmithJSON = "var Metalsmith=require('metalsmith');\nvar markdown=require('metalsmith-markdown');\nvar layouts=require('metalsmith-layouts');\nvar permalinks=require('metalsmith-permalinks');\nvar fs=require('fs');\nvar Handlebars=require('handlebars');\n Metalsmith(__dirname)\n.metadata({\ntitle: \"Demo Title\",\ndescription: \"Some Description\",\ngenerator: \"Metalsmith\",\nurl: \"http://www.metalsmith.io/\"})\n.source('')\n.destination('" + folderUrl + "/MetalsmithOutput')\n.clean(false)\n.use(markdown())\n.use(layouts({engine:'handlebars',directory:'" + folderUrl + "/Layout'}))\n.build(function(err,files)\n{if(err){\nconsole.log(err)\n}});"

                                    axios.post(this.baseURL + '/flows-dir-listing', {
                                            filename: mainMetal,
                                            text: metalsmithJSON,
                                            type: 'file'
                                        })
                                        .then((res) => {
                                            console.log('Now previewing: ' + this.$store.state.fileUrl.replace(/\\/g, "\/"))
                                            let previewFile = this.$store.state.fileUrl.replace(/\\/g, "\/");
                                            previewFile = folderUrl.replace('/var/www/html', '');
                                            console.log(previewFile.replace('Pages' + nameF, ''));

                                            axios.delete(this.baseURL + '/flows-dir-listing/0?filename=' + folderUrl + '/Preview')
                                                .then((res) => {

                                                    console.log(res);
                                                })
                                                .catch((e) => {
                                                    console.log(e)
                                                })

                                        })
                                        .catch((e) => {
                                            console.log(e)
                                        })

                                })
                                .catch((err) => {
                                    console.log('error while creating metalsmithJSON file' + err)
                                })

                            this.$message({
                                showClose: true,
                                message: 'File Saved!',
                                type: 'success'
                            });
                        })
                        .catch((e) => {
                            this.saveFileLoading = false
                            this.$message({
                                showClose: true,
                                message: 'File not saved! Please try again.',
                                type: 'error'
                            });
                            console.log(e)
                        })

                })
                .catch((e) => {
                    console.log(e)
                })

        })
        .catch((e) => {
            console.log('error while creating metalsmithJSON file' + e)
            this.$message({
                showClose: true,
                message: 'Cannot save file! Some error occured, try again.',
                type: 'danger'
            });
        })
}

PS 不要太努力去理解代码,因为需要解释,但这对于理解情况来说不是必需的。谢谢。

axios

回答

9

bluebird可能对你有帮助。如果你的环境支持async/await,那么使用它很好。

3

@sabakugaara 谢谢,但我刚刚创建了一个执行 axios.post 部分的函数,并且每次循环时我都调用该函数。每次迭代函数调用的响应确实比 for 循环迭代下一个所花费的时间晚一点。因此不匹配,但最后它给出了所需的结果。

this.previewFucnction(mainMetal,responseMetal,nameF,Layout)

           })  
      }
    },
 previewFucnction(mainMetal,responseMetal,nameF,Layout){
      var folderUrl = this.$store.state.fileUrl;
      console.log("folderUrl:",folderUrl)
      return axios.post('http://localhost:3030/flows-dir-listing', {
                  filename: mainMetal,
                  text: responseMetal,
                  type: 'file'
              }).then( (response) => {
2

我猜测当循环运行更多次迭代时,后期回调效率不高。

5

promise.then是异步的,for loop是同步的。所以回调看起来像是延迟了。

也许我不明白你的意思,:)

7

@sabakugaara 是的,你明白我的意思。

那么,我怎样才能使 promise.then 与我的 for 循环同步?

9

不可以。promise.then必须是同步的,那么如果你像这样编写同步代码:

const p = new Promise(function (resolve, reject) {
  return resolve('promise done')
})
p.then(function(result) {
  console.log(result)
})
console.log('before promise')
// output is:
// before promise
// promise done

Promise.each或者其他一些工具可能会有帮助。