简体   繁体   English

等待一项功能完成后再继续?

[英]Wait for one function to finish before continuing?

When running the following code tidied in functions or not, it still writes to my file incorrectly.当运行以下代码整理的函数时,它仍然错误地写入我的文件。 One thing that did work was wrapping those functions inside of a setTimeout method, with the seconds somewhere around 10. I just didn't like the idea of hardcoding those values and taking anymore time to complete than it should.有效的一件事是将这些函数封装在一个 setTimeout 方法中,秒数大约为 10。我只是不喜欢硬编码这些值并花费更多时间来完成的想法。 What's a better way of going about this?有什么更好的方法来解决这个问题? I need help understanding async/await a little more as you can tell but what better way than to fail and ask for help!我需要帮助理解 async/await,正如您所知道的那样,但还有什么比失败并寻求帮助更好的方法!

  genPriceChangeScripts: async () => {
    const priceScript = `...`;

    const changeData = await get24hrChange();

    const globalCmds = [];
    const globalPol = [];

    const filtered = changeData.filter(function (item) {
      return (
        !item.symbol.includes("BTCUSDT_") && !item.symbol.includes("ETHUSDT_")
      );
    });

    async function scripts() {
      filtered.forEach((e) => {
        const data = e.symbol;

        const change = priceScript.replace("CHANGE", data);

        fs.writeFile(
          `../scripts/price_change/${data.toLowerCase()}_price_change.sh`,
          change,
          function (err) {
            if (err) return console.log(err);
          }
        );
      });
      console.log("scripts finished");
    }
    scripts();

    async function commands() {
      for (let i = 0; i < filtered.length; i++) {
        var pushCmds = `"#($CURRENT_DIR/scripts/price_change/${filtered[
          i
        ].symbol.toLowerCase()}_price_change.sh)"`;
        globalCmds.push(pushCmds);
      }

      const commands = globalCmds.join("\n");

      const cmdsWithComment = commands.concat("\n#CHANGE3");

      fs.readFile("../binance.tmux", "utf-8", (err, data) => {
        if (err) {
          throw err;
        }

        const addCmds = data.replace("#CHANGE1", cmdsWithComment);

        fs.writeFile("../binance.tmux", addCmds, (err) => {
          if (err) {
            throw err;
          }
        });
      });
      console.log("cmds finished");
    }
    commands();

    async function pols() {
      for (let i = 0; i < filtered.length; i++) {
        const pushPol = `"\\#{${filtered[
          i
        ].symbol.toLowerCase()}_price_change}"`;
        globalPol.push(pushPol);
      }

      const pol = globalPol.join("\n");

      const polWithComment = pol.concat("\n#CHANGE4");

      fs.readFile("../binance.tmux", "utf-8", (err, data) => {
        if (err) {
          throw err;
        }

        const addPol = data.replace("#CHANGE2", polWithComment);

        fs.writeFile("../binance.tmux", addPol, (err) => {
          if (err) {
            throw err;
          }
        });
      });
      console.log("pols finished");
    }
    pols();

    return prompt.end();
  },

The issue is that making a function async doesn't make it automatically wait for anything asynchronous going on inside it问题是使函数async不会使其自动等待内部发生的任何异步操作

async / await is syntax "sugar" for working with Promises, and Promises only async / await是用于处理 Promises 的语法“糖”,并且适用于 Promises

So, if you use the promise version of writeFile/readFile like so所以,如果你像这样使用 writeFile/readFile 的承诺版本

import * as fs from 'fs/promise';

you can write your code as follows你可以写你的代码如下

genPriceChangeScripts: async() => {
    const priceScript = `...`;

    const changeData = await get24hrChange();

    const globalCmds = [];
    const globalPol = [];

    const filtered = changeData.filter(function (item) {
        return (!item.symbol.includes("BTCUSDT_") && !item.symbol.includes("ETHUSDT_"));
    });

    async function scripts() {
        const promises = filtered.map((e) => {
            const data = e.symbol;

            const change = priceScript.replace("CHANGE", data);

            return fs.writeFile(`../scripts/price_change/${data.toLowerCase()}_price_change.sh`, change);
        });
        await Promise.all(promises);
        console.log("scripts finished");
    }
    await scripts();

    async function commands() {
        for (let i = 0; i < filtered.length; i++) {
            var pushCmds = `"#($CURRENT_DIR/scripts/price_change/${filtered[i].symbol.toLowerCase()}_price_change.sh)"`;
            globalCmds.push(pushCmds);
        }

        const commands = globalCmds.join("\n");

        const cmdsWithComment = commands.concat("\n#CHANGE3");

        const data = await fs.readFile("../binance.tmux", "utf-8");
        const addCmds = data.replace("#CHANGE1", cmdsWithComment);
        await fs.writeFile("../binance.tmux", addCmds);
        console.log("cmds finished");
    }
    await commands();

    async function pols() {
        for (let i = 0; i < filtered.length; i++) {
            const pushPol = `"\\#{${filtered[i].symbol.toLowerCase()}_price_change}"`;
            globalPol.push(pushPol);
        }
        const pol = globalPol.join("\n");
        const polWithComment = pol.concat("\n#CHANGE4");
        const data = await fs.readFile("../binance.tmux", "utf-8");
        const addPol = data.replace("#CHANGE2", polWithComment);
        await fs.writeFile("../binance.tmux", addPol);
        console.log("pols finished");
    }
    await pols();

    return prompt.end();
},

You need to await the File System operations in order to wait for the asynchronous functions to return a response before proceeding.您需要await 文件系统操作,以便在继续之前等待异步函数返回响应。

await fs.readFile and await fs.writeFile await fs.readFileawait fs.writeFile

See this question for further explanation and examples.有关进一步的解释和示例,请参阅此问题

This is in addition to adding await to your other async functions to propagate the promise chain correctly.这是除了将await添加到您的其他async函数以正确传播承诺链之外。

Not that I'm saying all your code works, but here are the kind changes I would make to get you in the correct direction:并不是说我说你的所有代码都有效,但这里是我会做的一些改变,让你朝着正确的方向前进:

// code above
  function scripts(){
    const a = [];
    filtered.forEach(e=>{
      const data = e.symbol, change = priceScript.replace('CHANGE', data);
      a.push(new Promise((resolve, reject)=>{
        fs.writeFile(`../scripts/price_change/${data.toLowerCase()}_price_change.sh`,
          change,
          err=>{
            if(err){
              reject(err);
            }
            else{
              resolve();
            }
          }
        );
      }));
    });
    return Promise.all(a);
  }
  await scripts();
// code below

Well... actually I would define the function somewhere else or not use it at all, but I think this is what you need to see.嗯...实际上我会在其他地方定义函数或者根本不使用它,但我认为这是你需要看到的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何继续等待一个功能完成? - How to wait for one function to finish before continuing? 在继续之前等待一个功能完成的正确方法? - Proper way to wait for one function to finish before continuing? 在继续之前等待一个 function 完成的最佳方法是什么? - what the best way to wait for one function to finish before continuing? 等待函数完成,然后再继续使用JavaScript - Wait for a function to finish before continuing in javascript 等待函数完成,然后再继续执行$ .each函数中的下一个循环 - wait for the function to finish before continuing to the next loop in a $.each function javascript-等到功能完成再继续 - javascript- Wait till function finish before continuing 获取功能以等待后期中间件保存完成后再继续 - Getting a function to wait for a post middleware save to finish before continuing 如何在继续之前等待递归 function 完全完成? - How can I wait for a recursive function to completely finish before continuing? 节点 - 在继续之前等待地图完成 - Node - wait for map to finish before continuing 等待JS对PHP的调用完成,然后继续 - Wait for a JS call to PHP to finish before continuing
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM