[英]Multiple sync functions with inside async functions
I have a little problem with async functions (inside functionSync1 there is an async funcion). 我的异步函数有一个小问题(在functionSync1里面有一个异步函数)。 I have this code:
我有以下代码:
main() {
functionSync1();
functionSync2();
}
functionSync1() {
console.log('start');
let promise =
Promise.resolve(this.localStorage.getItem('myItem').toPromise());
promise.then((val) => console.log(val));
}
functionSync2() {
console.log('end');
}
For some reasons I can't modify code of main()
, so I would like to modify functionSync1()
in order to wait the end of the function until console.log(val)
is executed. 由于某些原因,我无法修改
main()
代码,因此我想修改functionSync1()
,以等待函数结束,直到执行console.log(val)
为止。
Now console.log('end')
is executed before console.log(val)
, so the output is: 现在
console.log('end')
在console.log(val)
之前执行,因此输出为:
start
end
myItemValue
I need this: 我需要这个:
start
myItemValue
end
Any ideas? 有任何想法吗?
You can create the output you describe using a promise queue: 您可以使用promise队列创建描述的输出:
const queue = Promise.resolve();
function enqueue(task, ...args) { return queue = queue.then(() => task(...args)); }
functionSync1(){
console.log('start');
enqueue(() => this.localStorage.getItem('myItem').toPromise())
.then((val) => console.log(val));
}
functionSync2(){
enqueue(() => console.log('end'));
}
But you should really just change main
. 但是您实际上应该只更改
main
。 Everything else is a workaround. 其他一切都是解决方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.