简体   繁体   English

如何将 async/await 与 Promises 结合起来?

[英]How to combine async/await with Promises?

In the below code have I createPost() inside an async function, but I don't want to use await on it, so it blocks execution of the rest of the function.在下面的代码中,我在async函数中使用了createPost() ,但我不想在其上使用await ,因此它阻止了函数其余部分的执行。 That is why I used then .这就是我使用then

The outer async function have lots of other functions that use await , so that can't be changed.外部async函数有许多其他函数使用await ,因此无法更改。

Question

Since createPost() is a async / await function (see below).由于createPost()是一个async / await函数(见下文)。 How can it resolve/reject to then / catch in the outer function?它如何在外部函数中解析/拒绝then / catch

module.exports = async (p) => {
  // lots of code here
  
 const t = await function1();      

    // lots of code here
    createPost(p).then(message => {
      // lots of code here
      console.log("ok " + message);
    }).catch(message => {
      console.log("failed " + message);
    });
};

createPost()创建邮政()

module.exports = async (p) => {
  // lots of code here
  try {
    const r = await getStat();
  } catch (error) {
    console.log(error);
  };
};

async / await is a more modern equivilant to .then / .catch . async / await是一个更现代的equivilant来.then / .catch
In this case you have mixed the syntaxes of both.在这种情况下,您混合了两者的语法。
You don't need try / catch blocks when using .then ,使用.then时不需要try / catch块,
just like you don't need to declare a function as async when using the try / catch syntax.就像在使用try / catch语法时不需要将函数声明为async

Other than that there's no reason they can't work together in seperate functions.除此之外,没有理由它们不能在单独的功能中一起工作。

module.exports = (p) => {
  createPost(p).then(message => {
    console.log("ok " + message);
  }).catch(message => {
    console.log("failed " + message);
  });
};

createPost():

module.exports = async (p) => {
  try {
    const r = await getStat();
  } catch (error) {
    console.log(error);
  };
};

An async decleration on a function is redundant and wrong if you're not using the await keyword inside.如果您没有在内部使用await关键字,则函数上的async是多余且错误的。

await/async are often referred to as syntactic sugar, and let us wait for something (eg an API call), giving us the illusion that it is synchronous in an actual asynchronous code, which is a great benefit. await/async 通常被称为语法糖,让我们等待一些东西(例如 API 调用),给我们一种在实际异步代码中它是同步的错觉,这是一个很大的好处。

The things you want to acheive with async/await is is possible with promises but the advantages of async/await.你想用 async/await 实现的事情可以用 promises 来实现,但是 async/await 的优点。 let's an example with this code:让我们以这段代码为例:

 const makeRequest = () => //promise way getJSON() .then(data => { return data }) makeRequest(); const makeRequest = async () => { //async await way const data = await getJSON(); return data; } makeRequest()

Why is async/await prefered over promise?为什么 async/await 比 promise 更受欢迎?

  1. Concise and clean - We didn't have to write .then and create an anonymous function to handle the response, or give a name data to a variable that we don't need to use.简洁干净- 我们不必编写 .then 并创建一个匿名函数来处理响应,或者为我们不需要使用的变量命名数据。 We also avoided nesting our code.我们还避免了嵌套我们的代码。 async/await is a lot cleaner. async/await 更干净。

  2. Error handling - Async/await makes it finally possible to handle both synchronous and asynchronous errors with the same try/catch format.错误处理- Async/await 最终可以使用相同的 try/catch 格式处理同步和异步错误。

  3. Debugging - A really good advantage when using async/await is that it's much easier to debug then promises for 2 reasons: 1) you can't set breakpoints in arrow functions that return expressions (no body).调试- 使用 async/await 的一个非常好的优势是调试比 promise 容易得多,原因有两个:1)您不能在返回表达式(无主体)的箭头函数中设置断点。 2) if you set a breakpoint inside a .then block and use debug shortcuts like step-over, the debugger will not move to the the following .then because it only “steps” through synchronous code. 2) 如果在 .then 块中设置断点并使用 step-over 等调试快捷方式,则调试器将不会移动到后面的 .then,因为它只会“单步执行”同步代码。

  4. Error stacks - The error stack returned from promises chain gives us no idea of where the error occured and can be misleading.错误堆栈- 从承诺链返回的错误堆栈让我们不知道错误发生在哪里并且可能会产生误导。 async/await gives us the error stack from async/await points to the function that contains the error which is a really big advantage. async/await 为我们提供了从 async/await 指向包含错误的函数的错误堆栈,这是一个非常大的优势。

"What changes do I need to make to createPost() so I can use then/catch in the outer function?" “我需要对createPost()进行哪些更改才能在外部函数中使用 then/catch?” - ——

All you need is to do is return a promise in outer function (using new Promise(...) or defer pattern ), And async function always return a new promise, Don't worry about multilayer promises, It will get flatten anyway.您需要做的就是在外部函数中返回一个承诺(使用new Promise(...)defer pattern ),并且异步函数总是返回一个新的承诺,不要担心多层承诺,无论如何它都会变平。 (like: await Promise.resolve(Promise.resolve(Promise.resolve("msg"))) -> "msg" ) (例如: await Promise.resolve(Promise.resolve(Promise.resolve("msg"))) -> "msg" )

"How do I specify message that the outer function gets?" “如何指定外部函数获得的消息?” - It depend, Depend on when you want to pull it. - 这取决于,取决于你什么时候想拉它。

This is common in async world.这在异步世界中很常见。 There is a pattern called defer pattern , Lets do an example:有一种模式叫做defer pattern ,让我们举个例子:

 function deferred() { let methods; const promise = new Promise((resolve, reject) => { methods = { resolve, reject }; }); return Object.assign(promise, methods); } const delay = ms => new Promise(ok => setTimeout(ok, ms)); async function myAsyncFunc() { let defer = deferred(); // create an async function and called immediately, In orther to use await inside... Although you can use `.then` pattern also. (async function () { await delay(2000); console.log("2s passed") defer.resolve("msg") })(); await delay(3000); console.log("3s passed") return defer } myAsyncFunc().then(console.log); // "msg"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM