简体   繁体   English

如何在执行下一个之前等待函数完成?

[英]How to await Function to finish before executing the next one?

// The Below code already contains the suggestions from the answers and hence works :) // 下面的代码已经包含了答案中的建议,因此有效:)

within the below script I tried to fully execute the 'createDatabase' function before the .then call at the end starts to run.在下面的脚本中,我尝试在最后的 .then 调用开始运行之前完全执行“createDatabase”函数。 Unfortunately I couldn't figure out a solution to achieve just that.不幸的是,我无法找到实现这一目标的解决方案。

In generell the flow should be as followed:一般来说,流程应该如下:

  1. GetFiles - Fully Execute it GetFiles - 完全执行它
  2. CreateDatabase - Fully Execute it (while awaiting each .map call to finish before starting the next) CreateDatabase - 完全执行它(在开始下一个之前等待每个 .map 调用完成)
  3. Exit the script within the .then call在 .then 调用中退出脚本

Thanks a lot for any advise :)非常感谢您的任何建议:)

const db = require("../database")
const fsp = require("fs").promises
const root = "./database/migrations/"

const getFiles = async () => {
  let fileNames = await fsp.readdir(root)
  return fileNames.map(fileName => Number(fileName.split(".")[0]))
}

const createDatabase = async fileNumbers => {
  fileNumbers.sort((a, b) => a - b)
  for (let fileNumber of fileNumbers) {
    const length = fileNumber.toString().length
    const x = require(`.${root}${fileNumber.toString()}.js`)
    await x.create()
  }
}

const run = async () => {
  let fileNumbers = await getFiles()
  await createDatabase(fileNumbers)
}

run()
  .then(() => {
    console.log("Database setup successfully!")
    db.end()
    process.exitCode = 0
  })
  .catch(err => {
    console.log("Error creating Database!", err)
  })

The x.create code looks as follows: x.create 代码如下所示:

const dbQ = (query, message) => {
  return new Promise((resolve, reject) => {
    db.query(query, (err, result) => {
      if (err) {
        console.log(`Error: ${err.sqlMessage}`)
        return reject()
      }
      console.log(`Success: ${message}!`)
      return resolve()
    })
  })
}

x.create = async () => {
  const query = `
    CREATE TABLE IF NOT EXISTS Country (
      Code CHAR(2) UNIQUE NOT NULL,
      Flag VARCHAR(1024),
      Name_de VARCHAR(64) NOT NULL,
      Name_en VARCHAR(64) NOT NULL,

      Primary Key (Code)
    )`

  const result = await dbQ(query, "Created Table COUNTRY")
  return result
}

If you want each x.create to fully execute before the next one starts, ie this is what I interpret where you say while awaiting each .map call to finish before starting the next - then you could use async/await with a for loop as follows:如果您希望每个x.create在下一个开始之前完全执行,即这就是我while awaiting each .map call to finish before starting the next所说的解释 - 那么您可以使用 async/await 和 for 循环作为如下:

const createDatabase = async fileNumbers => {
  fileNumbers.sort((a, b) => a - b);
  for (let fileNumber of fileNumbers) {
    const x = require(`.${root}${fileNumber.toString()}.js`);
    await x.create();
  })
}

However, this also assumes that x.create() returns a Promise - as you've not shown what is the typical content of .${root}${fileNumber.toString()}.js file is, then I'm only speculating然而,这也假设x.create()返回一个 Promise - 因为你没有展示.${root}${fileNumber.toString()}.js文件的典型内容是什么,那么我只是投机

The other interpretation of your question would simply require you to change createDatabase so that promises is actually an array of promises (at the moment, it's an array of undefined您的问题的另一种解释只是要求您更改createDatabase以便promises实际上是一个承诺数组(目前,它是一个undefined的数组

const createDatabase = async fileNumbers => {
  fileNumbers.sort((a, b) => a - b);
  const promises = fileNumbers.map(fileNumber => {
    const x = require(`.${root}${fileNumber.toString()}.js`);
    return x.create();
  })
  await Promise.all(promises);
}

Now all .create() run in "parallel", but createDatabase only resolves onces all promises returned by x.create() resolve - again, assumes that x.create() returns a promise现在,所有.create()在“并行”运行,但createDatabase只解决onces通过返回的所有承诺x.create()决心-再次,假设x.create()返回一个承诺

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

相关问题 如何在React中执行下一个函数之前完成所有获取? - How to finish all fetch before executing next function in React? 在执行下一个函数之前等待循环完成 - wait for for loop to finish before executing next function Javascript如何在触发下一个函数之前正确等待一个函数? - Javascript how to properly await for a function before triggering the next one? 在执行下一个函数之前等待循环完成填充数组 - wait for loop to finish populating array before executing next function Javascript在执行下一行之前不等待函数完成 - Javascript doesn't wait for function to finish before executing next line Javascript:等待循环中的函数在下一次迭代之前完成执行 - Javascript: wait for function in loop to finish executing before next iteration 如何在继续下一行代码之前等待 .map() 完成执行 - How to wait for .map() to finish executing before continuing on to next lines of code 在执行另一个函数之前,如何使jquery等待一个函数完成? - How can I make jquery wait for one function to finish before executing another function? 在继续之前完成功能的执行 - Finish function executing before proceeding 如何在执行另一个功能之前等待某个功能完成? - How do I wait for a certain function to finish before executing another one?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM