相关疑难解决方法(0)

节点JS Promise.all和forEach

我有一个类似于数组的数组,它暴露了异步方法.async方法调用返回数组结构,进而显示更多异步方法.我正在创建另一个JSON对象来存储从此结构获取的值,因此我需要小心跟踪回调中的引用.

我编写了一个强力解决方案,但我想学习一个更惯用或更干净的解决方案.

  1. 对于n级嵌套,该模式应该是可重复的.
  2. 我需要使用promise.all或类似的技术来确定何时解决封闭的例程.
  3. 并非每个元素都必然涉及进行异步调用.所以在嵌套的promise.all中我不能简单地根据索引对我的JSON数组元素进行赋值.尽管如此,我确实需要在嵌套的forEach中使用promise.all之类的东西,以确保在解析封闭例程之前已经完成了所有属性赋值.
  4. 我正在使用bluebird promise lib,但这不是必需的

这是一些部分代码 -

var jsonItems = [];

items.forEach(function(item){

  var jsonItem = {};
  jsonItem.name = item.name;
  item.getThings().then(function(things){
  // or Promise.all(allItemGetThingCalls, function(things){

    things.forEach(function(thing, index){

      jsonItems[index].thingName = thing.name;
      if(thing.type === 'file'){

        thing.getFile().then(function(file){ //or promise.all?

          jsonItems[index].filesize = file.getSize();
Run Code Online (Sandbox Code Playgroud)

javascript asynchronous node.js promise

105
推荐指数
2
解决办法
18万
查看次数

在node.js中使用带有async/await的文件系统

我想在一些文件系统操作中使用async/await.通常async/await工作正常,因为我使用babel-plugin-syntax-async-functions.

但是使用这段代码,我遇到了names未定义的if情况:

import fs from 'fs';

async function myF() {
  let names;
  try {
    names = await fs.readdir('path/to/dir');
  } catch (e) {
    console.log('e', e);
  }
  if (names === undefined) {
    console.log('undefined');
  } else {
    console.log('First Name', names[0]);
  }
}

myF();
Run Code Online (Sandbox Code Playgroud)

当我将代码重建到回调地狱版本时,一切正常,我得到了文件名.谢谢你的提示.

javascript fs node.js async-await

95
推荐指数
10
解决办法
8万
查看次数

标签 统计

javascript ×2

node.js ×2

async-await ×1

asynchronous ×1

fs ×1

promise ×1