javascript - 通过节点的异步/等待不需要按预期顺序返回结果 - 使用什么正确模式?
问题描述
我正在使用标准节点需要模式,该模式需要文件(send.js)并允许访问这些模块导出的功能。
如果我在标准回调模式中使用所有必需的模块,我会得到预期的结果和正确的执行顺序。
但是,如果我尝试转到等待/异步模式,则函数执行不正确(随机)。
在 send.js 中:
var request = require(`request`);
module.exports = {
message: function message(psid,text,callback) {
var options = {
headers: {
'Content-Type': `application/json`
},
url:`https://graph.facebook.com/v4.0/me/messages?access_token=12345`,
body:JSON.stringify({
'messaging_type': `RESPONSE`,
'recipient':{
'id':``+psid+``
},
'message': {
'text': text
}
})
};
request.post(options, function (err, res, body){
if(err){
console.log(err);
callback(err)
}
else{
callback(null,body)
}
});
},
}
在 app.js 中:
回调模式 - 适用于嵌套函数,按顺序执行的函数:
send.message(psid,'text'function(err,result){
send.message(psid,result,function(err,response){
console.log(response);
});
});
异步等待模式 - 以错误的顺序返回消息,随机执行顺序:
async function test(){
const one = await send.getUser(psid,'text',function(){});
const two = await send.message(psid,`1`,function(){});
const three = await send.message(psid,`2`,function(){});
const four = await send.message(psid,`3`,function(){});
const five = await send.message(psid,`4`,function(){});
}
test();
这是因为所需的模块使用回调 - 如果是这样,我如何转换send.js
以便可以在 app.js 中使用异步等待模式?
谢谢你。
解决方案
async/await仅适用于 Promise。您需要修改 send.js 以使用 Promise。一种方法是使用request-promise而不是 request 模块。
var rp = require(`request-promise`);
module.exports = {
message: function message(psid,text) {
var options = {
method: 'POST',
headers: {
'Content-Type': `application/json`
},
uri:`https://graph.facebook.com/v4.0/me/messages?access_token=12345`,
body:{
'messaging_type': `RESPONSE`,
'recipient':{
'id':``+psid+``
},
'message': {
'text': text
}
}
};
return rp(options);
},
}
async function test(){
const one = await send.getUser(psid);
const two = await send.message(psid,`1`);
const three = await send.message(psid,`2`);
const four = await send.message(psid,`3`);
const five = await send.message(psid,`4`);
}
test();
您还需要修改 getUser 方法以使用 request-promise。
推荐阅读
- count - Qlik Sense - 具有多个逻辑/过滤器实施的 COUNT Measure
- go - 为什么这些 Go 类型不相同?
- angular - 离子侧边菜单 - view.ts 中的触发功能
- android - 如何设置 MutableLiveData 的值
() 在 Kotlin 中是不利的吗? - c++ - 使用 ffmpeg API 将 pcm_alaw 类型的音频数据包装成 MKA 音频文件
- excel - 做直到什么都没找到
- json - angular.json 资产:使用通配符作为名称
- c - 如何shell命令注入文件
- node.js - 在某些情况下,将 nodejs 缓冲区转换为字符串并返回到缓冲区会产生不同的结果
- typescript - 在 Typescript 中指定具有至少一个已知属性的对象