我正在对Bing Web Search API进行API调用,并在响应中遇到错误。
这里是代码:
await webSearchApiClient.web.search(searchText).then(result => {
console.log('Results API', result)
return result
}).catch((err) => {
throw err;
})
我遇到的问题是结果确实会返回(控制台日志'Results API'打印预期的返回值),但是return语句没有传递该值。其余代码被编写为异步的,当我在调用API函数的代码中打印值时,会得到以下信息:
Line 1: Results API {"_type": "SearchResponse","queryContext": {"originalQuery":...
Line 2: Returned Results undefined
我尝试将result
设置为其他变量没有成功
我也使用redux,这是调度调用的代码和redux操作中的代码(第二个控制台日志是redux操作:]
const onSearchResults = async () => {
dispatch(getWebResults(searchText))
dispatch(getImageResults(searchText))
}
export const getWebResults = (searchText) => {
return async dispatch => {
const onStart = () => {
dispatch({ type: GET_WEB_RESULTS_STARTED });
}
const onSuccess = (response) => {
dispatch({ type: GET_WEB_RESULTS_SUCCESS, payload: response });
return response;
}
const onError = (error) => {
dispatch({ type: GET_WEB_RESULTS_FAILURE, payload: error });
return error;
}
try {
onStart();
const webResults = await BingWebSearchApi(searchText);
console.log('Returned Results', webResults)
return onSuccess(webResults)
} catch(error) {
return onError(error)
}
}
}
代替这样做
await webSearchApiClient.web.search(searchText).then(result => {
console.log('Results API', result)
return result
}).catch((err) => {
throw err;
})
由于return语句用于then函数范围,因此您应该像这样返回promise
return webSearchApiClient.web.search(searchText);
然后在您的redux动作中执行类似操作
(...)
try {
onStart();
BingWebSearchApi(searchText).then((webResults)=> {
console.log('Returned Results', webResults);
onSuccess(webResults);
});
} catch(error) {
return onError(error)
}