Skip to content

Instantly share code, notes, and snippets.

@tuchk4
Created December 7, 2017 10:27
Show Gist options
  • Save tuchk4/036803bb38586a0c4e605dce01a5658b to your computer and use it in GitHub Desktop.
Save tuchk4/036803bb38586a0c4e605dce01a5658b to your computer and use it in GitHub Desktop.
#1 ― async / await (KharkivJS)
function squareAfter2Seconds(x) {
return new Promise(resolve => {
setTimeout(() => {
resolve(x * x);
}, 2000);
});
}
async function calc() {
const a = await squareAfter2Seconds(10);
const b = await squareAfter2Seconds(20);
const c = await squareAfter2Seconds(30);
console.log(a + b + c);
}
calc();
@kazminigor1988
Copy link

kazminigor1988 commented Dec 7, 2017

function squareAfter2Seconds(x) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(x * x);
    }, 2000);
  });
}

async function calc() {
  let a;
  let b;

  squareAfter2Seconds(10)
      .then(result => a = result);

  squareAfter2Seconds(20)
      .then(result => b = result);

  const c = await squareAfter2Seconds(30);

  console.log(a + b + c);
}

calc();

@tuchk4
Copy link
Author

tuchk4 commented Dec 7, 2017

Работать будет, но не самое красивое решение

@egorkel-da14
Copy link

egorkel-da14 commented Dec 7, 2017

function squareAfter2Seconds(x) {
  return new Promise( res => {
    setTimeout(() => {
      res(x * x);
    }, 2000);
  });
}

async function calc() {
  const a = squareAfter2Seconds(10);
  const b = squareAfter2Seconds(20);
  const c = squareAfter2Seconds(30);

  console.log(await a + await b + await c);
}

calc();

@tuchk4
Copy link
Author

tuchk4 commented Dec 7, 2017

да, самый ок вариант.

убрал ссылку на гист из топика, а то не интересно будет

@bozheville
Copy link

Поскольку не успел - хоть сахару добавлю

async function calc() {
  const [ a, b, c ] = [ 10, 20, 30 ].map( n => squareAfter2Seconds( n ) );
  console.log(await a + await b + await c);
}

@tuchk4
Copy link
Author

tuchk4 commented Dec 7, 2017

@bozheville

Если совсем упороться, можно еще и без переменных )
(btw но так делать не нужно никогда)

async function calc() {
  console.log(
    await [ 10, 20, 30 ]
    .map(async x => await squareAfter2Seconds(x))
    .reduce(async (a, b) => await a + await b)
  )
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment