简体   繁体   English

异步等待嵌套相关的Promise调用

[英]async await with nested dependent Promise call

I'm trying to learn more about async, await Promises and all these, I have understood the concept behind it, but I'm getting troubles when it comes to nest logic of these Promises. 我试图了解有关异步,等待Promises和所有这些的更多信息,我已经了解了其背后的概念,但是在涉及这些Promise的嵌套逻辑时遇到了麻烦。 In theory what I have understood is that the whole async await would make your code look more synchronous, meaning that everything that expects a promise to be the result you use the await. 从理论上讲,我所理解的是整个异步等待将使您的代码看起来更加同步,这意味着所有期望诺言的结果都是您使用等待的结果。 Main goal with this code is to return from the list of directories+files that came from readdirPromisify, filter, and only give me a list of files. 这段代码的主要目标是从目录列表中返回来自readdirPromisify的目录和文件,过滤并仅给我一个文件列表。 using the stat.isFile(). 使用stat.isFile()。 If anyone can help I would appreciate. 如果有人可以帮助,我将不胜感激。 thanks! 谢谢!

const fs = require("fs");
const { exec } = require("child_process");
const { promisify } = require("util");
const [, , ...args] = process.argv;
const isOptionDirectory = promisify(fs.stat);
const readdirPromisify = promisify(fs.readdir);
const [packageName] = args;

const test = async function() {
  const dirs = await readdirPromisify(__dirname);
  const files = await dirs.filter(async file => {
    const option = await isOptionDirectory(file);
    return option.isFile();
  });
  return files;
};

console.log(test().then(val => console.log(val)));

filter does not support promises. filter器不支持诺言。 The promise returned by the async function will be treated as a truthy value. async function返回的promise将被视为真实值。

You will want to use Promise.all : 您将要使用Promise.all

async function test() {
  const paths = await readdirPromisify(__dirname);
  const options = await Promise.all(paths.map(isOptionDirectory));
  return paths.filter((_, i) => options[i].isFile());
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM