Dhi*_*ade 29 https request node.js node-modules
我正在寻找将 async / await 与 https post 一起使用的方法。请帮帮我。我已经在下面发布了我的 https 帖子代码片段。如何使用异步等待。
const https = require('https')
const data = JSON.stringify({
todo: 'Buy the milk'
})
const options = {
hostname: 'flaviocopes.com',
port: 443,
path: '/todos',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': data.length
}
}
const req = https.request(options, (res) => {
console.log(`statusCode: ${res.statusCode}`)
res.on('data', (d) => {
process.stdout.write(d)
})
})
req.on('error', (error) => {
console.error(error)
})
req.write(data)
req.end()
Run Code Online (Sandbox Code Playgroud)
Ris*_*ale 45
基本上,您可以编写一个返回 a 的函数,Promise
然后您可以将async
/await
与该函数一起使用。请参阅以下内容:
const https = require('https')
const data = JSON.stringify({
todo: 'Buy the milk'
});
const options = {
hostname: 'flaviocopes.com',
port: 443,
path: '/todos',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': data.length
},
};
async function doSomethingUseful() {
// return the response
return await doRequest(options, data);
}
/**
* Do a request with options provided.
*
* @param {Object} options
* @param {Object} data
* @return {Promise} a promise of request
*/
function doRequest(options, data) {
return new Promise((resolve, reject) => {
const req = https.request(options, (res) => {
res.setEncoding('utf8');
let responseBody = '';
res.on('data', (chunk) => {
responseBody += chunk;
});
res.on('end', () => {
resolve(JSON.parse(responseBody));
});
});
req.on('error', (err) => {
reject(err);
});
req.write(data)
req.end();
});
}
Run Code Online (Sandbox Code Playgroud)
小智 5
我也遇到了这个问题,找到了这篇文章,并使用了 Rishikesh Darandale(这里)的解决方案。
该AWAIT文件规定的经营者的await用来等待承诺。不需要从函数返回承诺。您可以创建一个承诺并对其调用 await 。
async function doPostToDoItem(myItem) {
const https = require('https')
const data = JSON.stringify({
todo: myItem
});
const options = {
hostname: 'flaviocopes.com',
port: 443,
path: '/todos',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': data.length
},
};
let p = new Promise((resolve, reject) => {
const req = https.request(options, (res) => {
res.setEncoding('utf8');
let responseBody = '';
res.on('data', (chunk) => {
responseBody += chunk;
});
res.on('end', () => {
resolve(JSON.parse(responseBody));
});
});
req.on('error', (err) => {
reject(err);
});
req.write(data)
req.end();
});
return await p;
}
Run Code Online (Sandbox Code Playgroud)
您只能将 async-await 与 Promises 一起使用,并且 Node 的核心 https 模块没有内置的Promise支持。因此,您首先必须将其转换为Promise格式,然后才能使用 async-await 。
https://www.npmjs.com/package/request-promise
该模块已将核心http模块转换为promisified版本。你可以用这个。
归档时间: |
|
查看次数: |
19118 次 |
最近记录: |