【发布时间】:2018-05-18 05:44:53
【问题描述】:
我在理解 Promise 功能的工作原理时遇到了一些问题,我以前使用过 Bluebird,但我想尝试学习新的 await/async 标准,以便提高程序员的水平。我使用了 async/await 并在我认为合适的地方创建了 Promise,但是这些功能仍然无序执行。
我正在使用 Webpack 在最新版本的 Node 上运行它,我没有收到任何有意义的错误。它运行良好,只是没有像预期的那样。我运行时的输出是:
Searching the Web for: Test String
Web search Completed!
Promise { <pending> }
Response Handler Completed!
理想情况下,我希望它回应:
Searching the Web for: Test String
Response Handler Completed
Web search 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 -
另外,你应该在错误时拒绝()!
-
也许使用 fetch api 会更简单,它会返回一个 promise 并且有点像
$.ajax: developer.mozilla.org/en-US/docs/Web/API/Fetch_API -
我将尝试使用 fetch 而不是 https,该模块上似乎没有那么多文档。谢谢各位!
-
Promises 是 ES2015 (ES6) 的一部分,
async/await是 ES2017 的一部分。
标签: javascript node.js promise ecmascript-2017