gpt4 book ai didi

javascript - 从另一个函数解析函数内的 promise

转载 作者:行者123 更新时间:2023-12-01 00:17:24 25 4
gpt4 key购买 nike

我想从speak函数中解析updateGuider函数,如下所示:

tutor();

async function tutor(){
console.log('tutor function initiated..');
// wait until updateGuider function resolves
await updateGuider('default');
// The expected result is to reach this line after updateGuider resolves, but we can't so far!
console.log('Procccess Ends');


}
// Not working unless we use var instead of let?!
let updateGuiderResolve;

function updateGuider(state){
return new Promise((resolve) => {
updateGuiderResolve = resolve;
switch(state) {
case 'default':
speak();
break;
}

});
}


async function speak(){
console.log('entered speak')
setTimeout(function(){
//after 5 seconds we resolve the updateGuider from speak function
updateGuiderResolve();
},5000)

}

如您所见,代码不起作用(预期结果是 5 秒后看到 console.log('Procccess Ends'));

我注意到,如果我将 let updateGuiderResolve 更改为 var updateGuiderResolve 一切正常!为什么?

最佳答案

let 的问题是(正如错误消息所解释的那样)您是 trying to use the variable before it has been initialised :您正在 let updateGuiderResolve; 声明上方调用 tutor()

但实际上,解析器函数根本不需要这个全局/静态共享变量。相反,让 speak 创建并返回 Promise 本身:

async function tutor() {
console.log('tutor function initiated..');
await updateGuider('default');
console.log('Procccess Ends');
}

async function updateGuider(state) {
switch(state) {
case 'default':
return speak();
}
}

function speak() {
console.log('entered speak')
return new Promise(function(resolve) {
setTimeout(resolve, 5000);
});
}

tutor().catch(console.error);

关于javascript - 从另一个函数解析函数内的 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59672512/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com