使用async / await合并并发请求和顺序请求

时间:2018-07-26 12:44:11

标签: javascript node.js ecmascript-6 promise async-await

我使用async / await,试图尽快执行三个请求。

getIndependentThingOnegetIndependentThingTwo返回数据,而不向其端点提交任何参数。 getDependentThing但是需要id返回的列表的第一个元素的getIndependentThingTwo属性。我有点原则上尝试遵循this pizza post中概述的内容。至少在精神上。

const getIndependentThingOne = async () => {
  const url = `${root}/1`
  return axios.get(url)
}

const getIndependentThingTwo = async () => {
  const url = `${root}/2`
  return axios.get(url)
}

const getDependentThing = async ([{ id }]) => {
  const url = `${root}/3/${id}`
  return axios.get(url)
}

const getIndependentThingOneAndDependentThing = async () => {
  const { data: listFromIndependentThingTwo } = await getIndependentThingTwo()
  const { data: listFromDependentThing } = await getDependentThing(
    listFromIndependentThingTwo
  )
  return {
    listFromIndependentThingTwo,
    listFromDependentThing
  }
}

const getAllData = async () => {
  const [
    { data: listFromIndependentThingOne },
    { listFromIndependentThingTwo, listFromDependentThing }
  ] = await Promise.all([
    getIndependentThingOne(),
    getIndependentThingOneAndDependentThing()
  ])
  console.log('DONE')
  console.log({ listFromIndependentThingOne })
  console.log({ listFromIndependentThingTwo })
  console.log({ listFromDependentThing })
}

getAllData()

虽然可行,但我想知道这是否是构造这些请求的最佳方法。返回最后两个值的对象并在此处对其进行销毁似乎有点不正确

const [
  { data: listFromIndependentThingOne },
  { listFromIndependentThingTwo, listFromDependentThing }
]

使用async / await进行这种操作是否有更惯用的模式?

4 个答案:

答案 0 :(得分:1)

我不会编写额外的getIndependentThingOneAndDependentThing函数,尤其是async / await不会。我宁愿采用简单的普通then语法,并在getAllData内进行所有操作:

const getIndependentThingOne = () => axios.get(`${root}/1`);
const getIndependentThingTwo = () => axios.get(`${root}/2`);
const getDependentThing = ([{id}]) => axios.get(`${root}/3/${id}`);

const getData = ({data}) => data;

async function getAllData() {
  const promiseOne = getIndependentThingOne().then(getData);
  const promiseTwo = getIndependentThingTwo().then(getData);
  const promiseThree = promiseTwo.then(getDependentThing).then(getData);
//                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

  const [listFromThingOne, listFromThingTwo, listFromThingThree] = await Promise.all([
    promiseOne,
    promiseTwo,
    promiseThree,
  ]);
  console.log('DONE')
  console.log({ listFromThingOne })
  console.log({ listFromThingTwo })
  console.log({ listFromThingThree })
}

getAllData()

(是否应将.then(getData)移到getThing函数内部,如async () => (await axios.get(…)).data一样,优先考虑)

答案 1 :(得分:1)

aysnc/await 的基本示例:

console.log('person1: shoe ticket');
console.log('person2: shoe ticket');

const preMovie = async () => {
	const promiseGirlFriendBringingTickets = new Promise((resolve, reject) => {
		setTimeout(() => {
			resolve('ticket');
		}, 3000);
	});

	const addButter  = new Promise((resolve, reject) => {
		resolve('butter');
	});

	const getPopcorn  = new Promise((resolve, reject) => {
		resolve('popcorn');
	});

	let ticket = await promiseGirlFriendBringingTickets;

	console.log(`girlfriend: i have the ${ticket}`);
	console.log('boyfriend: we should go in');
	console.log('girlfriend: no i am hungry');

	let popcorn = await getPopcorn;

	console.log(`boyfriend: I got some ${popcorn}`);
	console.log('boyfriend: we should go in');
	console.log('girlfriend: I need butter on my popcorn');

	let butter = await addButter;

	console.log(`boyfriend: I got some ${butter} on popcorn`);
	console.log('boyfriend: anything else baby ?');
	console.log('girlfriend: Lets go we are getting late');

	return ticket;
}
preMovie().then((m) => console.log(`person3: shoes ${m}`));

console.log('person4: shoe ticket');
console.log('person5: shoe ticket');

答案 2 :(得分:0)

“ dependendThing”可以对它所依赖的事物做出承诺:

const getDependentThing = async (dependentThingTwo) => {
  const { data: listFromIndependentThingTwo } = await dependentThingTwo;
 return getDependentThing(
  listFromIndependentThingTwo
 );
}

这样,您可以获得的结果如下:

const dependentThing = independentThingTwo();
const [listFromTwo, dependentThing] = await Promise.all([dependentThing, getDependendThing(dependentThing)]);

答案 3 :(得分:0)

基本模式是:

async function getStuff() {
  // Kick off thing one request, don't wait!
  const thingOnePromise = getIndependentThingOne();

  // Kick off things two request, don't wait quite yet.
  const [{id}] await getIndependentThingTwo();

  await dependentThingThree(id);
  await thingOnePromise;
}

换句话说,您启动了第一个请求,而没有等待它。在功能完成之前,您需要稍后等待。