我的异步不会因我的等待而停止-那时AWAIT等待什么? [英] My Async won't stop for my Await - What does AWAIT wait for then?

查看:61
本文介绍了我的异步不会因我的等待而停止-那时AWAIT等待什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在进入Node,并陷入异步编程的世界.

I am getting into Node, and being thrown into the world of async programming.

我在Mozilla的网站上仔细阅读了这篇文章(以及许多其他有关异步和等待关键字的链接):

I thoroughly read this article on Mozilla's site (along with many other links teaching about the async and await keywords):

https://developer.mozilla.org/zh-CN/docs/Learn/JavaScript/Asynchronous/Async_await

https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await

我有一个正在开始的项目,它将需要大量的数据库调用,一个又一个.有些查询将依赖于前一个查询的结果.话虽如此,我决定我会更好地练习并编写一些测试代码.

I have a project I am starting that will require numerous database calls, one after another. Some queries will rely upon the previous one's results. That being said, I decided I better practice and write some testing code.

这是我的测试代码:

var users, items;

const getData = async function(){
    // This is a DB call. Will take
    // a little bit of time to complete.

    setTimeout(() => {
        var queryResults = "A list of items";
        items = queryResults;
    }, 1000);

    return items;
}

const getUsers = async function(){
    setTimeout(() => {
        var queryResults = "A list of items";
        users = queryResults;
    }, 1000);

    return users;
}

const init = async function(){
    var itemSuccess = await getData();
    var userSuccess = await getUsers();

    console.log(`Here is your items: ${items}, and here are your users: ${users}`);
}

init();

我的代码失败,原因:

Here is your items: undefined, and here are your users: undefined

所以我自然而然地回到了Mozilla.我重新阅读了文档,并尝试了一些更改.仍然没有成功.最终,我回到了上面的原始代码.

So naturally I headed back to Mozilla. I re-read the docs, and tried a few changes. Still, no success. Ultimately I ended up back at my original code above.

我不明白为什么这失败了.我正在通过使用超时来模拟查询所花费的时间.如果async做到了,这两个函数都应该返回它们的值,然后我的控制台日志应打印出正确的结果.

I cannot see why this is failing. I am simulating the time a query would take by using a timeout. If async does what it says, both functions should return their value, and then my console log should print out the correct results.

有人看到我要去哪里了吗?

Does anyone see where I am going wrong?

谢谢.

推荐答案

向我们展示您的REAL代码以及其中的实际数据库调用,我们可以为您提供更具体的帮助,包括向您展示工作代码.请抵制用伪代码发布问题的诱惑.显示真实代码,如果您向我们显示真实代码,我们可以为您提供更快,更好的帮助.

Show us your REAL code with the actual database calls in it and we can help you much more specifically, including showing you working code. Please resist the temptation to post questions with pseudo-code. Show real code and we can help you so much faster and better if you show us the real code.

await 仅在您 await 一个对您感兴趣的内容完成或出错时会解决或拒绝的诺言时有用.

await ONLY does something useful when you await a promise that resolves or rejects when something you are interested in completes or errors.

以某种方式知道何时执行 setTimeout()或任何其他异步操作是一件很神奇的事情.

It has no magic to somehow know when a a setTimeout() or any other asynchronous operation is done doing whatever it does.

因此,当您执行此操作时:

So, when you do this:

var itemSuccess = await getData();

然后, getData()看起来像这样:

const getData = async function(){
    // This is a DB call. Will take
    // a little bit of time to complete.

    setTimeout(() => {
        var queryResults = "A list of items";
        items = queryResults;
    }, 1000);

    return items;
}

您最终要做的是:

var itemSuccess = await undefined 

因为您的 getData()函数不返回承诺,实际上,它甚至不返回项目,因为它在计时器之前返回,因此 items (此处似乎未正确声明)尚未收到其值.

because your getData() function doesn't return a promise and, in fact, it doesn't even return the items because it returns BEFORE your timer so items (which doesn't appear to be declared properly here) has not yet received its value.

所以,我建议您从基础开始,然后阅读 await 的实际功能.确保您了解它如何与承诺交互,因为它仅在与承诺一起使用时才有用.并且,然后学习如何使异步操作返回在异步操作完成时连接到的promise.然后,直到那时,您才能正确使用 await .

So, I would suggest you start back with the basics and go read what await really does. Make sure you understand how it interacts with a promise since it's only useful when used with a promise. And, then learn how to make your asynchronous operations return promises that are connected to when your asynchronous operations complete. Then, and only then, can you make proper use of await.

在一个组织良好的世界中,您要确保所有异步操作都已经返回了promises,然后可以 async/await .then() .catch()来控制所有异步操作的流程.在许多情况下,这涉及到学习诺言界面,无论您使用什么.例如,现代版本的node.js在 fs.promises 中具有文件系统的完整promise接口.

In a well organized world, you make sure that all your asynchronous operations are already returned promises and then you can async/await and .then() and .catch() to control the flow of all your asynchronous operations. In many cases, this involves learning the promise interface for whatever you're using. For example, modern versions of node.js have an entire promise interface for the file system in fs.promises.

在某些情况下,您正在使用的某些库可能不存在Promise接口,您可能必须将异步操作包装在Promise中以创建自己的Promise接口. util.promisify()内置在node.js中,以帮助您实现这一目标.

In a few cases, there may not exist a promise interface for some library you're using and you may have to wrap the asynchronous operation in a promise to make your own promise interface. util.promisify() is built-into node.js to help you do that.

如果显示ACTUAL代码,包括正在使用的数据库以及要尝试进行的实际数据库调用,则此处的某人可能会为您提供在数据库上使用promise接口的正确方法.此伪代码使我们无法为您提供具体帮助.如果没有您的实际代码并且不知道您在特定数据库中进行的实际数据库调用,那么,除了向数据库使用Promise接口并学习如何正确使用这些Promise之外,我们很难提供更多建议.很乐意提供更具体的帮助,但我们需要看到您的REAL代码才能做到这一点.

If you show the ACTUAL code, include which database you're using and the actual database call you're trying to make, then someone here can probably help you with the proper way to use the promise interface on the database. This pseudo code prevents us from helping you that specifically. Without your actual code and knowing the actual DB calls you're making in a specific DB, it's hard for us to advise much more than go use the promise interface to your database and learn how to use those promises properly. Happy to help more specifically, but we need to see you REAL code to do that.

最后,在Javascript中,如果您要从任何异步回调中为更高范围的对象分配值,则您做错事的机率高达99.99%.实际可以使用该值的唯一位置是在回调本身内部或在您从那里调用并将该值传递给的函数中.因此,当您执行 items = queryResults 时,在您上方的两个作用域中声明了 items ,那么请警惕这对您不起作用.这不是您使用Javascript异步代码进行编程的方式,不仅是出于样式方面的原因,而且还因为它不起作用.

And, lastly in Javascript if you're assigning a value to something in a higher scope from within any asynchronous callback, there's a 99.99% chance you're doing things wrong. The only place you can actually use that value is inside the callback itself or in a function that you call from there and pass the value to. So, when you do items = queryResults, where items is declared in a couple scopes above you, then alarm bells should go off that this is not going to work for you. It's not how you program with asynchronous code in Javascript, not just for style reasons, but because it doesn't work.

这篇关于我的异步不会因我的等待而停止-那时AWAIT等待什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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