为了处理 promise ,我返回并将它们链接到 .then()
。但是,我必须使用需要回调但不返回 promise 的第三方库。
为了清楚起见,举一个假的例子:
person.sayHello()
.then( response => introduceMyself() )
.then( name => externalLibrary.storeAndGetInfo(name) )
.then( info => saySomeInfo(info) )
.catch( err => console.log(err) );
introduceMyself(){
return asyncFunctionToGetAndSayMyName();
}
sayDomeInfo(info){
console.log(info);
}
我的问题是externalLibrary.storeAndGetInfo
需要这些参数:
storeAndGetInfo(string, callback(valueThatINeedForMyNextChainedFunction));
我感觉我可以将外部库函数包装在可链接函数(返回 promise 的函数)中,然后使用 the library q
推迟并解析回调函数,但随后我陷入困境,因为我不知道实际实现它。或者还有其他办法吗?
PS,以防万一它有所作为,这是在 angularjs
中应用程序
最佳答案
您应该使用返回延迟 promise 的函数来包装外部库的调用:
function promisedStore (name) {
var deferred = Q.defer(); //initialize deferred
externalLibrary.storeAndGetInfo(name, function(error, result) {
if (error) {
deferred.reject(new Error(error)); //reject promise if error in cb
} else {
deferred.resolve(result); //resolve promise if no error in cb
}
});
return deferred.promise;
}
关于javascript - 将基于回调逻辑的库函数集成到 Promise 链中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42532665/