gpt4 book ai didi

javascript - 将可多次调用的Javascript回调转换为promise

转载 作者:行者123 更新时间:2023-11-29 21:43:56 25 4
gpt4 key购买 nike

有没有办法将可以多次调用的带回调的 Javascript 调用转换为 promise?

说,

scan(function(result) {
// this is actually a Bluetooth device scan (Cordova), and
// will return something when a device is found.
// So this can be called more than once.
});

然后把它包装成一个 promise?

function scanP {
return new Promise(function(resolve, reject) {
scan(function (result) {
resolve(result); // attempt to call repeatedly, but doesn't work.
});
});
}

scanP(function(result) {
// check if this device is what we want.
})
.catch(function(err) {
// handle error
});

我还需要这种模式来订阅来自蓝牙设备的数据。 promise 不适合这个任务吗?

编辑:我正在使用 Bluebird。

最佳答案

Promise 只解决一次。如果想多次解决它,那么您需要的不是 promise。

您可能需要自定义事件(在浏览器中),Node 的 EventEmitterStream(继承 EventEmitter,具有 .pipe,可选缓冲)。如果您想要的只是一个回调链解决方案,那么编写您自己的解决方案似乎并不难。

关于javascript - 将可多次调用的Javascript回调转换为promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31915578/

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