子功能和异步等待状态

时间:2019-06-13 22:21:33

标签: javascript function async-await axios

在我的一个API端点中,我从Web上获取了一个json资源(1)并对其进行编辑以适合我的需求。在树的“最低”或“最深”部分,我试图获取另一个资源并将其添加到最终的json对象中。我对async / await相对较新,但是由于我看到了使用async / await的优点(或收益),因此尝试摆脱“旧” Promise

(1)中的对象看起来像;

const json = {
  date,
  time,
  trips: [{
    name,
    legs: [{
        id
      },
      {
        id
      }
    ]
  }]
};

这是我“重新格式化”并更改json对象的方式;

{
  date,
  time,
  trips: json.trips.map(trip => formatTrip(trip))
};

function formatTrip(trip) {
  return {
    name,
    legs: trip.legs.map(leg => formatLeg(leg))
  };
};

async function formatLeg(leg) {
  const data = await fetch();

  return {
    id,
    data
  };
};

这个问题是,在我“重新格式化/编辑”原始json以查看我想要的方式(并通过所有format...函数运行)之后,legs对象为空{{ 1}}。

我认为这可能是由于async / await承诺未完成。我还读到,如果子功能使用异步/等待,所有更高的功能也必须使用异步/等待。

为什么?如何重写代码以使其正常工作并看起来不错?谢谢!

编辑:

我根据Randy的回答更新了代码。 {}仍未定义/为空。

getLegStops(leg)

1 个答案:

答案 0 :(得分:0)

两件事导致您想要嵌套这些Promises:

  1. 关于回调和承诺的旧思维方式
  2. 相信软件过程必须与数据结构匹配

如果我理解正确,看来您只需要处理一次Promise。

赞:

async function getLegs(){
 return trip.legs.map(async leg => await fetch(...)); // produces an array of Promises
}

const legs = Promise.all(getLegs());

function formatLegs(legs) {
   // do something with array of legs
};

function formatTrip(){
   //format final output
}

编辑:根据您在下面的评论,此代码段代表了我所展示的内容以及您的目标。请仔细检查您的代码。

const arr = [1, 2, 3, ];

const arrPromises = arr.map(async v => await new Promise((res) => res(v)));
const finalPromise = Promise.all(arrPromises);
console.log(finalPromise.then(console.log));