繁体   English   中英

在继续下一行之前,我如何确保已兑现承诺?

[英]How do I make sure that a promise is resolved before proceeding to the next lines?

说我有以下几点:

var myFuncResult = null;                
browser.executeScript( "return myFunc();").then( function(i){
    myFuncResult = i;
    // console.log([ "myFunc is: ", i]); this is fine
});
console.log([ "myFunc is: ", myFuncResult]);
//do something about myFunctResult
myFuncResult.doSomethingElse();

现在,外部console.log正在记录为空,因为它已经在承诺被解决之前执行了。 我该如何预防? 如何确保我提供的功能在console.log之前先执行? 在继续其余行之前,我需要先初始化myFuncResult。

没有办法做您想要的,这是设计使然。 承诺将异步运行,因此console.log语句将始终在解决承诺之前运行。 解决诺言后使console.log语句运行的正确方法是添加另一个then子句,如下所示:

var myFuncResult = null;                
browser.executeScript( "return myFunc();").then( function(i){
    myFuncResult = i;
    // console.log([ "myFunc is: ", i]); this is fine
}).then(function() {
    console.log([ "myFunc is: ", myFuncResult]);
});

您确实需要小心处理错误条件,因为如果promise被拒绝, then子句的第一个参数不会被调用。

是的,这可以导致意大利面条的承诺,但是(略)比回调地狱要好。 享受JavaScript!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM