Javascript JS:不确定何时使用Promise.resolve()而不是返回新承诺
我不确定返回Javascript JS:不确定何时使用Promise.resolve()而不是返回新承诺,javascript,Javascript,我不确定返回新承诺与使用承诺.resolve()的用法是什么,我想确保我对这些的理解是正确的 鉴于以下3个功能: function testFunc() { return Promise.resolve().then(() => { //anything asynchronous in here has now become synchronous and //execution of result of t
新承诺
与使用承诺.resolve()
的用法是什么,我想确保我对这些的理解是正确的
鉴于以下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++;
}
}
testFunc()
将在到达并执行logMe()之前完全执行
对于testFunc2()
,如果按以下顺序执行:
testFunc2();
logMe();
我的理解是,在本例中,while循环中的逻辑仍然会同步执行并延迟以下函数的执行,logMe()
,但是解析将被异步处理。这并不容易。您必须使用test Func.then(logMe())
。另一种选择是在异步函数中运行这两个函数:
async function run() {
await testFunc();
logMe();
}
wait
非常简单,它运行函数并等待它完成,然后运行下一行async
就在那里,因此await
可以工作(await在异步函数之外不工作)
我更喜欢异步
/等待
,但更多的人更喜欢。然后
。这正是您想要使用的,两者非常相似。这并不是那么容易。您必须使用test Func.then(logMe())
。另一种选择是在异步函数中运行这两个函数:
async function run() {
await testFunc();
logMe();
}
wait
非常简单,它运行函数并等待它完成,然后运行下一行async
就在那里,因此await
可以工作(await在异步函数之外不工作)
我更喜欢
异步
/等待
,但更多的人更喜欢。然后
。这正是您想要使用的,两者非常相似。如果我正确理解您想要实现的目标,那么您希望在循环内异步执行操作
函数testFunc2(){
常量承诺=[]
for(设i=0;i{
控制台日志(i);
解决()
}));
}
返回承诺。全部(承诺);
}
函数logMe(){
设i=0;
而(i<5){
console.log(“内部日志我”);
i++;
}
}
(异步()=>{
等待testFunc2()
logMe();
})();
如果我正确理解了您试图实现的目标,那么您希望在循环内异步执行操作
函数testFunc2(){
常量承诺=[]
for(设i=0;i{
控制台日志(i);
解决()
}));
}
返回承诺。全部(承诺);
}
函数logMe(){
设i=0;
而(i<5){
console.log(“内部日志我”);
i++;
}
}
(异步()=>{
等待testFunc2()
logMe();
})();
谢谢。我只是想了解这些函数的作用以及它们如何影响不同级别的事件循环。我只是想了解这些函数的作用以及它们如何以不同的方式影响事件循环