gpt4 book ai didi

Javascript,一个带有回调处理程序的对象,如何将其重写为 await/async 样式?

转载 作者:行者123 更新时间:2023-11-29 17:43:08 31 4
gpt4 key购买 nike

我正在使用一个 api,它的对象提供回调处理程序,一个搜索功能。它看起来像这样:

function searchAndDoSomething(name){
let searchObj = new APIobj(para1,{onSearchComplete:searchCompleteHandler});
searchObj.search(name);
}
function searchCompleteHandler(result){
doSomething(result);
}

我的目标是让它变成这样:

Async Main(){
result = await searchAndDoSomething(name);
searchCompleteHandler(result);
}

但是如何重写searchAndDoSomething呢?

async searchAndDoSomething(name){
return new Promise(function(resolve){
let searchObj = new APIobj(para1,{onSearchComplete:resolve};//this will call a resolve function.
//and
resolve(name);//instead of searchObj.search will no effect too.
})
}

最佳答案

您的尝试很接近,但由于您需要显式创建 promise (因为 APIobj 不需要),因此您的函数没有理由异步。此外,您只想调用一次 resolve:

searchAndDoSomething(name) {
return new Promise((resolve) => {
const searchObj = new APIobj(para1, {onSearchComplete: resolve});
searchObj.search(name);
});
}

APIobj 大概有一种方法可以发出失败信号;如果是这样,你想调用 reject。例如,如果我猜测一个名为 onSearchError 的回调:

searchAndDoSomething(name) {
return new Promise((resolve, reject) => {
const searchObj = new APIobj(para1, {
onSearchComplete: resolve,
onSearchError: reject
});
searchObj.search(name);
});
}

然后你可以像这样使用它:

async Main() { // Note it's `async`, not `Async`
const result = await searchAndDoSomething(name); // note declaration
searchCompleteHandler(result);
}

async Main() {
searchCompleteHandler(await searchAndDoSomething(name));
}

关于Javascript,一个带有回调处理程序的对象,如何将其重写为 await/async 样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51839888/

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