为什么我必须使用等待才能获得承诺的结果?

发布于 2025-02-08 13:03:34 字数 550 浏览 2 评论 0原文

const delay = ms => new Promise(res => setTimeout(res, ms));

async function notInstant() {
  await delay(1);
  return 1;
}

(async function() {
 let a = notInstant();
 console.log(a);
 await delay(10000);
 console.log("Still a promise after 10 seconds even though the function only waits for 1 millisecond =>", a);
 a = await a;
 console.log("Printing directly after but now is resolved with the correct value", a);
})();

我知道我不应该依靠Settimeout来实现这类事情,但是我不明白为什么在10秒后仍会打印结果,即使该功能只需等待1毫秒,才能返回值。 然后使用等待使结果直接出于某种原因。

const delay = ms => new Promise(res => setTimeout(res, ms));

async function notInstant() {
  await delay(1);
  return 1;
}

(async function() {
 let a = notInstant();
 console.log(a);
 await delay(10000);
 console.log("Still a promise after 10 seconds even though the function only waits for 1 millisecond =>", a);
 a = await a;
 console.log("Printing directly after but now is resolved with the correct value", a);
})();

I know that I shouldn't rely on setTimeout for these kinds of things, but I don't understand why printing the result after 10 seconds still gives an unresolved promise even though the function called only waits for 1 millisecond before returning a value.
Then using await makes the result directly available for some reason.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

〆凄凉。 2025-02-15 13:03:34

此示例说明了您要观察到的原则:

let a = {};
console.log(a);
a.val = 1;
console.log(typeof a); // still an object even though `a` has a value
a = a.val;
console.log(typeof a); // now it's a number

Notintant返回的原始承诺将永远是一个承诺。 等待基本上从对您的承诺中提取解决值。 a最终在示例中成为一个值的唯一原因是,您将其设置为等待表达式的结果。

如果您想将a设置为其完成后的承诺结果,但请避免等待,您可以使用其,然后可以使用方法影响国家的变化,这样:

const delay = ms => new Promise(res => setTimeout(res, ms));

async function notInstant() {
  await delay(1);
  return 1;
}

(async function() {
 let a = notInstant();
 console.log(a);
 a.then(n => a = n);
 await delay(1000); 
 console.log("a has its value now; we waited long enough", a);
})();

这可能不是一个很好的遵循模式(重用变量代表承诺和价值),但希望它有助于教授原则。

This example illustrates the principle you're observing:

let a = {};
console.log(a);
a.val = 1;
console.log(typeof a); // still an object even though `a` has a value
a = a.val;
console.log(typeof a); // now it's a number

The original promise returned from notInstant will always be a promise. await basically extracts the resolved value from the promise for you. The only reason a ends up being a value in your example is that you're setting it to the result of the await expression.

If you wanted to set a to the result of its promise when it completes, but avoid awaiting it, you could use its then method to affect a state change, like this:

const delay = ms => new Promise(res => setTimeout(res, ms));

async function notInstant() {
  await delay(1);
  return 1;
}

(async function() {
 let a = notInstant();
 console.log(a);
 a.then(n => a = n);
 await delay(1000); 
 console.log("a has its value now; we waited long enough", a);
})();

That's probably not a great pattern to follow (reusing the variable to represent both the promise and the value), but hopefully it helps teach the principle.

寒冷纷飞旳雪 2025-02-15 13:03:34

从文档中:

等待的表达式导致异步函数执行暂停直到
承诺已解决(即,实现或拒绝),并恢复
实现后的异步功能执行。恢复时,
等待表达的价值是实现的诺言。

https:// https://developer.mozilla.org/en--en--en----en---------美国/文档/web/javascript/reference/operators/等待

因此,正如戴夫(Daveg)所述

from the docs:

The await expression causes async function execution to pause until a
Promise is settled (that is, fulfilled or rejected), and to resume
execution of the async function after fulfillment. When resumed, the
value of the await expression is that of the fulfilled Promise.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await

So, as mentioned by DaveG, with out calling the await, you are just holding the promise

栀子花开つ 2025-02-15 13:03:34

请注意,async函数返回承诺。
而且您需要等待才能获得承诺的价值。


这是

href =“ https://developer.mozilla.org/en-us/docs/web/javascript/reference/referenions/statement/ashync_function#return_value” rel =“ nofollow noreflow noreferrer”

将通过异步函数返回的值解决,或者被拒绝并在异步函数中丢弃或未被授予的例外。

Notice that async functions return a promise.
And you need await to get the value of the promise.


here is what MDN says about it:

Async Function's Return value

A Promise which will be resolved with the value returned by the async function, or rejected with an exception thrown from, or uncaught within, the async function.

叹倦 2025-02-15 13:03:34

当您使用等待函数()时,
该功能应返回承诺,
如果您等待等待,并且通过该功能返回的结果不承诺
等待没有任何效果。
因此,您需要告诉JS等待结果,并在两种决心或拒绝的情况下返回时给予承诺。
检查mdn documention

when you use await function(),
the function should return a promise,
and if you put await and the result return by that function is not promise
the await does not have any effect.
so you need to tell js to await for the result and give it a promise when you gonna return in two cases of resolve or reject.
check MDN Documention

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文