使用异步/等待与承诺的区别? [英] Difference of using async / await vs promises?

查看:93
本文介绍了使用异步/等待与承诺的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找有关在我的nodeJS应用中使用什么的答案.

I am looking for a answer on what to use in my nodeJS app.

我有处理我对mssql的通用dB访问的代码.这段代码是使用async函数编写的,然后我使用了一个Promise来调用该函数,并且一切正常.

I have code which handles my generic dB access to mssql. This code is written using an async functions and then I used a promise to call that function and all works fine.

随着我的应用程序越来越大,代码越来越大,我计划将一些逻辑移到函数中,然后调用它们.

As my app is getting bigger and code larger I am planning to move some of the logic into functions and then call them.

所以我的问题是:使用异步/等待和承诺的组合是否有缺点,还是真的没关系?

异步/等待使我更容易编写更具可读性的代码,因为在返回某些内容之前,我必须读写多个数据库,而我需要其中的一些结果.

Async / await makes it easier to write more readable code as I have to read and write to multiple db’s before I return something and I need results of some of these.

所以问题是什么是更好的方法? 已设置且无法更改的异步/正在等待的dB层 逻辑层async/await允许我异步/并在函数调用中等待,或者如果我接受逻辑承诺,那么我会在函数调用中陷入promise.

So the question is what is the better approach? Async / await on dB layer that’s set and can’t change The logic layer async / await which would allow me a async / and await on the function call or if I go with promise for logic then I am stuck with promise on function call.

因此,我希望有人可以给我更多的见解,除了能够编写更简洁的代码之外,它是否比另一个具有更多的优势.

So I hope someone can give me more insight if one has more advantages than the other, besides being able to write cleaner code.

推荐答案

async/await与承诺密切相关. async函数返回promise,而await是等待解决promise的语法糖.

async/await and promises are closely related. async functions return promises, and await is syntactic sugar for waiting for a promise to be resolved.

将promise和async函数混合使用的唯一缺点可能是代码的可读性和可维护性,但是您当然可以将异步函数的返回值用作promise,而对于返回的常规函数​​,可以使用await一个诺言.

The only drawback from having a mix of promises and async functions might be readability and maintainability of the code, but you can certainly use the return value of async functions as promises as well as await for regular functions that return a promise.

您是否选择另一个主要取决于可用性(您的node.js/浏览器是否支持async?)和您的审美偏好,但是有一个很好的经验法则(基于我当时的偏好)写作)可能是:

Whether you choose one vs the other mostly depends on availability (does your node.js / browser support async?) and on your aesthetic preference, but a good rule of thumb (based on my own preference at the time of writing) could be:

return asyncFunction()
.then(result => f1(result))
.then(result2 => f2(result2));

vs

const result = await asyncFunction();
const result2 = await f1(result);
return await f2(result2);

如果您需要嵌套的Promise:请使用async/await:

return asyncFunction()
.then(result => {
  return f1(result)
  .then(result2 => f2(result, result2);
})

vs

const result = await asyncFunction();
const result2 = await f1(result);
return await f2(result, result2);

如果您需要并行运行:请使用promises.

return Promise.all(arrayOfIDs.map(id => asyncFn(id)))

建议您可以在表达式中使用await来等待多个任务,例如:
*注意,这仍然会从左到右依次等待,如果您不希望出现错误,则可以.否则,由于

It has been suggested you can use await within an expression to await multiple tasks like so:
*note, this still awaits in sequence from left to right, which is OK if you don't expect errors. Otherwise the behaviour is different due to fail fast behaviour of Promise.all()

const [r1, r2, r3] = [await task1, await task2, await task3];

(async function() {
  function t1(t) {
    console.time(`task ${t}`);
    console.log(`start task ${t}`);
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        console.timeEnd(`task ${t}`);
        resolve();
      }, t);
    })
  }

  console.log('Create Promises');
  const task1 = t1(100);
  const task2 = t1(200);
  const task3 = t1(10);

  console.log('Await for each task');
  const [r1, r2, r3] = [await task1, await task2, await task3];

  console.log('Done');
}())

但是与Promise.all一样,在发生错误的情况下也需要正确处理并行promise.您可以在此处了解更多信息.

But as with Promise.all, the parallel promises need to be properly handled in case of an error. You can read more about that here.

请注意不要将前面的代码与以下内容混淆:

Be careful not to confuse the previous code with the following:

let [r1, r2] = [await t1(100), await t2(200)];

function t1(t) {
  console.time(`task ${t}`);
  console.log(`start task ${t}`);
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      console.timeEnd(`task ${t}`);
      resolve();
    }, t);
  })
}
console.log('Promise');
Promise.all([t1(100), t1(200), t1(10)]).then(async() => {

  console.log('Await');
  let [r1, r2, r3] = [await t1(100), await t1(200), await t1(10)]
});

使用这两种方法并不等效. 了解有关区别的更多信息.

Using these two methods is not equivalent. Read more about the difference.

最后,Promise.all是一种更干净的方法,可以更好地扩展到任意数量的任务.

In the end, Promise.all is a cleaner approach that scales better to an arbitrary number of tasks.

这篇关于使用异步/等待与承诺的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆