基于当前平台创建承诺对象

Create a Promise object based on the current platform

本文关键字:承诺 对象 创建 平台 于当前      更新时间:2023-09-26

我正在使用Apache Cordova,并且在Promise对象方面遇到了多平台问题。

目前,我必须实例化这样的承诺:

var promise = new Promise(...) {
    //Implementation
}

这很好,但是如果应用程序在 Windows 平台上运行,我必须改用WinJS。喜欢这个:

var promise = new WinJS.Promise(...) {
    //Implementation
}

这将生成以下代码:

var promise;
if (cordova.platformId == "windows") {
    promise = new WinJS.Promise(...) {
        //Implementation
    }
} 
else {
    promise = new Promise(...) {
        //Exactly the same implementation as above
    }
}

这里的主要问题是我在每个承诺中复制实现,导致两个完全相同的代码块。因此,它更难维护。

有没有办法根据当前平台实例化正确的Promise,而不必复制代码两次?

如果Promise不存在,你可以把它分配给WinJS.Promise,然后像往常一样使用Promise

喜欢:

if (typeof Promise === 'undefined' && cordova.platformId === 'windows') {
  Promise = WinJS.Promise; // global assignment
}
// At this point you can use new Promise() as usual

当你在JS/Angular中开发时,你为什么不使用Angular Promise呢?

我的意思是$q,承诺/延迟对象的实现。

有关$q,请参阅文档