首页 > 解决方案 > 通过节点的异步/等待不需要按预期顺序返回结果 - 使用什么正确模式?

问题描述

我正在使用标准节点需要模式,该模式需要文件(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 中使用异步等待模式?

谢谢你。

标签: javascriptnode.jscallbackasync-await

解决方案


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。


推荐阅读