首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >对于这个例子,我应该使用异步等待吗?

对于这个例子,我应该使用异步等待吗?
EN

Stack Overflow用户
提问于 2020-06-18 03:51:50
回答 3查看 64关注 0票数 0

下面的示例似乎都适用于异步等待,如下所示:

代码语言:javascript
运行
AI代码解释
复制
import { db } from '../firebase';

const onAdd = async () => {
    await db.collection('FlashCards').add({
      originalText: newOriginalText,
      translatedText: newTranslatedText,
    });

  };

如果没有异步,就像这样等待:

代码语言:javascript
运行
AI代码解释
复制
import { db } from '../firebase';

const onAdd = () => {
    db.collection('FlashCards').add({
      originalText: newOriginalText,
      translatedText: newTranslatedText,
    });

  };

我用哪一种有什么区别吗?在本例中,使用异步等待是否有任何改进?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2020-06-18 04:06:58

我建议使用第一个片段。它确实有一个优势--如果你愿意的话,你可以等待onAdd完成。对于第二个示例,您可以执行它,并且代码将工作--将进行一个插入,但是您不能等待完成。

下面是一个简单的例子:

代码语言:javascript
运行
AI代码解释
复制
//simple delayed operation - prints a message after 2 seconds
async function delayedOperation(msg) {
  return new Promise(resolve => {
    setTimeout(() => {
      console.log("complete:", msg);
      
      resolve();
    }, 2000);
  });
}

//awaiting the operation
async function withAwait() {
  await delayedOperation("with await");
}

//not awaiting the operation
function withoutAwait() {
  delayedOperation("without await");
}

async function main() {
  console.log("before calling withAwait()");
  await withAwait();
  console.log("after calling withAwait()");
  
  console.log("before calling withoutAwait()");
  await withoutAwait();
  console.log("after calling withoutAwait()");
}

main();

正如你所看到的,withoutAwait本身是无法等待的。问题是它没有产生承诺,main()withoutAwait()中延迟的操作完成之前就完成了。

如果不需要await,则可以始终在函数中使用它,但不能使用它:

代码语言:javascript
运行
AI代码解释
复制
async function delayedOperation(msg) {
  return new Promise(resolve => {
    setTimeout(() => {
      console.log("complete:", msg);
      
      resolve();
    }, 2000);
  });
}

async function withAwait() {
  await delayedOperation("with await");
}

async function main() {
  console.log("before calling withAwait()");
  //not awaiting because we don't care whether it finishes before proceeding
  withAwait(); 
  console.log("after calling withAwait()");
}

main();

但是,检查操作是否完成是个好主意,否则您无法响应错误,甚至可能不知道它们发生了:

代码语言:javascript
运行
AI代码解释
复制
//WILL FAIL!
async function delayedOperation(msg) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {      
      reject(`problem when doing [${msg}]`);
    }, 2000);
  });
}

async function withAwait() {
  await delayedOperation("with await");
}

async function main() {
  console.log("before calling withAwait() and handling the error");
  try {
    await withAwait(); 
  } catch(e) {
    console.error(e);
  }
  console.log("after calling withAwait() and handling the error");
  
  console.log("before calling withAwait() - no handling");
  //not awaiting because we don't care whether it finishes before proceeding
  withAwait(); 
  console.log("after calling withAwait() - no handling");
}

main();

请注意,添加async而不是await将不允许您正确地await函数的结果。

代码语言:javascript
运行
AI代码解释
复制
async function delayedOperation(msg) {
  return new Promise(resolve => {
    setTimeout(() => {
      console.log("complete:", msg);
      
      resolve();
    }, 2000);
  });
}


// async function but not awaiting the operation
async function withoutAwait() {
  delayedOperation("without await");
}

async function main() {
  console.log("before calling withoutAwait()");
  //attempting to await the completion
  await withoutAwait();
  console.log("after calling withoutAwait()");
}

main();

因为withoutAwait()的主体没有await,所以当delayedOperation()返回承诺时,它就完成了,而不是在该承诺确定时完成。

票数 1
EN

Stack Overflow用户

发布于 2020-06-18 04:08:24

这取决于你期望什么行为。

正如Firebase文档中提到的,.add(...)方法是异步的。https://firebase.google.com/docs/firestore/manage-data/add-data#add_a_document

等待/异步函数确保存储执行完成。

如果不需要确保数据在onAdd函数调用后存储在数据库中,则可以不使用异步。

票数 1
EN

Stack Overflow用户

发布于 2020-06-18 04:11:08

异步/等待将确保您的进程将同步执行。因此,在完成onAdd()执行之前,代码的其余部分将不会被处理。尽管它取决于你的背景是否需要。

但是根据您的上下文,我认为异步/等待将是最好的。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62449359

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档