[英]JS: Unsure of when to use Promise.resolve() vs returning a new Promise
I am unsure how the usage of returning a new Promise
vs using a Promise.resolve()
and want to make sure my understanding of these are correct.我不确定返回
new Promise
与使用Promise.resolve()
的用法如何,并希望确保我对这些的理解是正确的。
Given these 3 functions below:鉴于以下这 3 个功能:
function testFunc() {
return Promise.resolve().then(() => {
//anything asynchronous in here has now become synchronous and
//execution of result of the function happens after this??
let i = 0;
while (i < 10000) {
console.log(i);
i++;
}
});
}
------
function testFunc2() {
return new Promise((resolve, reject) => {
//anything asynchronous in here is still asynchronous but the
//`resolve()` is then synchronous??
let i = 0;
while (i < 10000) {
if (i === 999) { resolve('I am a test func') };
i++;
}
})
}
------
//synchronous function
function logMe() {
let i = 0;
while (i < 10000) {
console.log("INSIDE LOG ME);
i++;
}
}
The way I understand it is that testFunc()
immediately resolves the Promise and anything within there becomes synchronous.我理解的方式是
testFunc()
立即解析 Promise 并且其中的任何内容都变得同步。 So if you were to execute:因此,如果您要执行:
testFunc();
logMe();
testFunc()
would fully execute before logMe()
was reached and executed. testFunc()
将在到达并执行logMe()
之前完全执行。
For the testFunc2()
, if it were executed in this order:对于
testFunc2()
,如果按此顺序执行:
testFunc2();
logMe();
I understand it as the logic inside, in this case the while loop, would still execute synchronously and delay the execution of the following function, logMe()
, but the resolve
would be treated asynchronously.我将其理解为内部逻辑,在这种情况下,while 循环仍将同步执行并延迟以下 function,
logMe()
的执行,但resolve
将被异步处理。
It's not that easy.那并没那么简单。 You would have to use
test Func.then(logMe())
.您将不得不使用
test Func.then(logMe())
。 Another option would be to run both functions in an asynchronous function:另一种选择是在异步 function 中运行这两个函数:
async function run() {
await testFunc();
logMe();
}
The await
is pretty simple - it runs the function and waits for it to finish, then runs the next lines. await
非常简单 - 它运行 function 并等待它完成,然后运行下一行。 async
is just there so that await
can work (await does not work outside of async functions). async
就在那里,以便await
可以工作(await 在 async 函数之外不起作用)。
I prefer async
/ await
, but many more prefer .then
.我更喜欢
async
/ await
,但更喜欢.then
。 It's just what you want to use, both are very similar.这正是你想要使用的,两者都非常相似。
If I understand correctly what you're trying to achieve, you want to asynchronously execute operation inside the loop.如果我正确理解您要实现的目标,则您希望在循环内异步执行操作。
function testFunc2() {
const promises = []
for(let i = 0; i<1000; i++){
promises.push(new Promise((resolve) => {
console.log(i);
resolve()
}));
}
return Promise.all(promises);
}
function logMe() {
let i = 0;
while (i < 5) {
console.log("INSIDE LOG ME");
i++;
}
}
(async() => {
await testFunc2()
logMe();
})();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.