简体   繁体   English

承诺后的操作顺序

[英]Order of operations after promises

I'm pretty new to JavaScript (using Node.js) and still learning.我对 JavaScript(使用 Node.js)还很陌生,还在学习。 I try to wrap around my head with promises and I got into this situation where I don't understand if there is a difference between this code:我试图用承诺环绕我的头,但我遇到了这种情况,我不明白这段代码之间是否有区别:

promiseFunc().then(() => {
     anotherPromiseFunc() // I dont need .then() here, just want to save some data to DB
 });
doSmthElse()

and this code:这个代码:

promiseFunc().then(async () => {
     await anotherPromiseFunc() // I dont need .then() here, just want to save some data to DB
 });
doSmthElse()

If I don't use .then() in the first case, does it mean there is a possibility that doSmthElse() will be executed before anotherPromiseFunc() is executed?如果我在第一种情况下不使用 .then( .then() ,是否意味着doSmthElse() anotherPromiseFunc()可能在 anotherPromiseFunc() 执行之前执行? So in order to prevent that, I have to add async / await ?所以为了防止这种情况,我必须添加async / await Or all code in .then() block is being waited to execute anyway before doing something else?或者.then()块中的所有代码在执行其他操作之前都在等待执行?

Note 1: I don't want to chain those promises, because there is more code in my case, but I just simplified it here.注意 1:我不想链接这些承诺,因为在我的案例中有更多代码,但我只是在这里简化了它。

Note 2: I don't use catch because if error will rip through I will catch it later.注意2:我不使用catch,因为如果错误会发生,我会在稍后捕获它。

If I don't use .then() in the first case, does it mean there is a possibility that doSmthElse() will be executed before AnotherPromise() is executed?如果我在第一种情况下不使用 .then( .then() ,是否意味着doSmthElse()有可能在 AnotherPromise( AnotherPromise()执行之前执行?

doSmthElse() is guaranteed to be executed before anything in the fulfillment handler¹ is executed. doSmthElse()保证在执行处理程序中的任何内容执行之前执行。 Promise fulfillment and rejection handlers are always invoked asynchronously. Promise 履行和拒绝处理程序总是异步调用。 That's true whether you declare the handler function using async or not.无论您是否使用async声明处理程序 function 都是如此。

For example:例如:

 console.log("before"); Promise.resolve(42).then(result => { console.log("within", result); }); console.log("after");

The output of that is:其 output 为:

before
after
within 42

So in order to prevent that, I have to add async / await ?所以为了防止这种情况,我必须添加async / await

Where you've added async / await in your example doesn't change when doSmthElse() is executed.当执行doSmthElse()时,您在示例中添加async / await的位置不会改变。

If you want doSmthElse() to wait until the promise has been fulfilled, move it into the fulfillment handler.¹如果您希望doSmthElse()等到 promise 已完成,请将其移动完成处理程序中。¹

If your code were inside an async function, you could use await instead, like this:如果您的代码在async function 中,则可以使用await代替,如下所示:

// Inside an `async` function
await promiseFunc().then(() => {
    anotherPromiseFunc();
});
doSmthElse()

That would do this:那会这样做:

  1. Call promiseFunc() and get the promise it returns调用promiseFunc()并获取它返回的 promise
  2. Hook up a fulfillment handler to that promise via then , returning a new promise;通过then将一个履行处理程序连接到该 promise,返回一个新的 promise; that new promise is the operand to await新的 promise 是await的操作数
  3. Wait for the promise from #1 to settle等待来自 #1 的 promise 解决
  4. When it does, your fulfillment handler is executed and runs anothterPromiseFunc() but doesn't wait for the promise it returns to settle (because, as you said, you're not returning that promise from the fulfillment handler).当它这样做时,您的履行处理程序将被执行并运行anothterPromiseFunc()等待它返回的 promise 解决(因为,正如您所说,您没有从履行处理程序返回 promise)。
  5. At this point, the promise from #2 is fulfilled because your fulfillment handler has (effectively) returned undefined , which isn't a thenable (loosely, a promise), so that value ( undefined ) is used to fulfill the promise from #2.此时,来自 #2 的 promise 已实现,因为您的实现处理程序(有效地)返回了undefined ,这不是一个thenable (松散地,一个承诺),因此该值( undefined )用于实现来自 #2 的 promise .
  6. Since the promise from #2 has been fulfilled, await is satisfied and doSmthElse() is executed.由于 #2 中的 promise 已满足,因此满足await并执行doSmthElse()

¹ the function you pass then as its first argument ¹您传递的then作为其第一个参数

I assume that Promise() just stands for some function call returning a Promise:我假设Promise()只代表一些 function 调用返回 Promise:

You could say that.then registers an event listener that runs as soon as the promise settles => the task is finished.您可以这样说。然后注册一个事件侦听器,该侦听器在 promise 稳定后立即运行 => 任务完成。 It still runs asynchronously So in your example doSmthElse will still run even if the promise hasn't been settled (so if the promise doesn't settle immediately doSmthElse will be called before the function inside.then)它仍然异步运行因此在您的示例中,即使 promise 尚未解决, doSmthElse仍将运行(因此,如果 promise 未立即解决, doSmthElse将在 ZC1C425264E68385D1ABZA4 内部调用之前调用)。

To let your code run "in order".让您的代码“按顺序”运行。 You would have to use await to ensure that doSmthElse is called after the promise settled or you could put doSmthElse into the.then block.您必须使用await来确保在doSmthElse解决之后调用 doSmthElse,或者您可以将doSmthElse放入 .then 块中。

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

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