약속 기능이 어떻게 작동하는지 이해하는 데 몇 가지 문제가 있습니다. 이전에 Bluebird를 사용했지만 프로그래머로 개선하기 위해 새로운 await/async 표준을 배우려고했습니다. 나는 async/await를 사용하여 적절한 기능을하지만 적절하게 작동하지 않는 약속을 만들었습니다.Await/Async와의 약속 사용 올바르게 함
Webpack을 사용하는 노드의 최신 버전에서 실행 중이므로 의미있는 오류가 발생하지 않습니다. 정상적으로 잘 돌아 가지 않습니다. 그것을 실행 내 출력은 다음과 같습니다
Searching the Web for: Test String
Response Handler Completed
Web search Completed
을 그리고 내 대답 처리기의 출력을 반환 :
Searching the Web for: Test String
Web search Completed!
Promise { <pending> }
Response Handler Completed!
은 이상적으로는 응답 싶습니다.
누구든지 내 실수를 감지 할 수 있습니까?
const https = require('https');
// Replace the subscriptionKey string value with your valid subscription key.
const subscriptionKey = '<samplekey>';
const host = 'api.cognitive.microsoft.com';
const path = '/bing/v7.0/search';
const response_handler = async (response) => {
return new Promise((resolve, reject) => {
let body = '';
response.on('data', (d) => {
body += d;
resolve(body);
});
response.on('end',() => {
console.log('\nRelevant Headers:\n');
for (const header in response.headers)
// header keys are lower-cased by Node.js
{
if (header.startsWith('bingapis-') || header.startsWith('x-msedge-')) { console.log(`${header}: ${response.headers[header]}`); }
}
body = JSON.stringify(JSON.parse(body), null, ' ');
//console.log('\nJSON Test Response:\n');
//console.log(body);
});
response.on('error', (e) => {
console.log(`Error: ${e.message}`);
});
console.log('Response Handler Completed!');
});
};
const bing_web_search = async (search) => {
return new Promise((resolve, reject) => {
console.log(`Searching the Web for: ${search}`);
const request_params = {
method: 'GET',
hostname: host,
path: `${path}?q=${encodeURIComponent(search)}&$responseFilter=${encodeURIComponent('Webpages')}&count=${50}`,
headers: {
'Ocp-Apim-Subscription-Key': subscriptionKey,
},
};
const req = https.request(request_params, response_handler);
console.log('Web search Completed!');
console.log(req.body);
req.end();
});
};
module.exports = {
search: async (search) => {
if (subscriptionKey.length === 32) {
const result = await bing_web_search(search);
console.log('Search Completed');
} else {
console.log('Invalid Bing Search API subscription key!');
console.log('Please paste yours into the source code.');
}
},
};
비동기 함수에서 약속을 반환하는 것은 의미가 없습니다. 그렇다면 비동기 일 필요는 없습니다. 그리고 절대로'resolve'라고 부르지 마십시오 –
또한 오류 발생시 거부()해야합니다! – falsarella
아마도 fetch api를 사용하면 더 간단해질 것이고, 약속을 되 돌리며'$ .ajax'와 같이 작동합니다 : https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API – HMR