Heim  >  Fragen und Antworten  >  Hauptteil

Verwenden Sie für den Betrieb die Schleifen async/await und forEach

<p>Gibt es Probleme bei der Verwendung von <code>async</code>/<code>await</code> innerhalb einer <code>forEach</code> Ich versuche, ein Array von Dateien zu durchlaufen und <code>await</code> für den Inhalt jeder Datei zu verwenden. </p> <pre class="brush:php;toolbar:false;">fs aus 'fs-promise' importieren asynchrone Funktion printFiles () { const files = waiting getFilePaths() // Gehe davon aus, dass diese Funktion ordnungsgemäß funktioniert files.forEach(async (file) => { const content = waiting fs.readFile(file, 'utf8') console.log(Inhalt) }) } printFiles()</pre> <p>Dieser Code funktioniert, aber gibt es dabei irgendwelche Probleme? Mir wurde gesagt, dass ich <code>async</code>/<code>await</code> nicht in Funktionen höherer Ordnung wie dieser verwenden sollte, also wollte ich fragen, ob es irgendwelche Fragen gibt. </p>
P粉010967136P粉010967136427 Tage vor477

Antworte allen(2)Ich werde antworten

  • P粉697408921

    P粉6974089212023-08-21 10:27:16

    使用ES2018,您可以大大简化上述所有答案:

    async function printFiles () {
      const files = await getFilePaths()
    
      for await (const contents of files.map(file => fs.readFile(file, 'utf8'))) {
        console.log(contents)
      }
    }

    查看规范:proposal-async-iteration

    简化后:

    for await (const results of array) {
        await longRunningTask()
      }
      console.log('I will wait')

    2018-09-10:最近这个答案引起了很多关注,请参阅Axel Rauschmayer的博客文章以获取有关异步迭代的更多信息。

    Antwort
    0
  • P粉094351878

    P粉0943518782023-08-21 09:14:18

    当然,代码确实可以工作,但我很确定它不会按照你的期望工作。它只是触发了多个异步调用,但printFiles函数在此之后立即返回。

    按顺序读取

    如果你想按顺序读取文件,确实不能使用forEach。相反,你可以使用现代的for … of循环,其中await将按预期工作:

    async function printFiles () {
      const files = await getFilePaths();
    
      for (const file of files) {
        const contents = await fs.readFile(file, 'utf8');
        console.log(contents);
      }
    }

    并行读取

    如果你想并行读取文件,确实不能使用forEach。每个async回调函数调用都会返回一个promise,但你却将它们丢弃而不是等待它们。相反,你可以使用map,并使用Promise.all等待得到的promise数组:

    async function printFiles () {
      const files = await getFilePaths();
    
      await Promise.all(files.map(async (file) => {
        const contents = await fs.readFile(file, 'utf8')
        console.log(contents)
      }));
    }

    Antwort
    0
  • StornierenAntwort