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

时间:2018-08-14 11:00:50

标签: javascript asynchronous promise async-await

我使用的是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.
    })
}

1 个答案:

答案 0 :(得分:4)

您的尝试已经结束,但是由于您需要显式创建一个Promise(因为#define ELAPSED_TIME(currentTime, startTime) (currentTime - startTime) 不需要),因此您的功能没有理由protected function parseAsyncCustomers($urls) { $promises = (function () use ($urls) { do { $uri = new Uri(current($urls)); $request = new Request('GET', $uri, ['User-Agent' => UserAgent::random()]); yield $this->httpClient->sendAsync($request, [ 'timeout' => 15, 'connect_timeout' => 15, ]); } while (next($urls) !== false); })(); (new \GuzzleHttp\Promise\EachPromise($promises, [ // Multiple Concurrent HTTP Requests 'concurrency' => 10, 'fulfilled' => function (ResponseInterface $response, $index) { $content = $response->getBody()->getContents(); $this->parseCustomerContent($content, $index); }, 'rejected' => function ($reason, $index) { // This is delivered each failed request if ($reason instanceof GuzzleException) { if ($this->reject++ > 30) { // how can stop sending next requests? } } }, ]))->promise()->wait(); } 。另外,您只想拨打一次APIobj

async

大概是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);
    });
}