Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/36.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js Request.post等待它结束NodeJS_Node.js_Post_Request - Fatal编程技术网

Node.js Request.post等待它结束NodeJS

Node.js Request.post等待它结束NodeJS,node.js,post,request,Node.js,Post,Request,我必须按顺序进行多个RESTAPI Post调用。第一个REST api的输出,第一个api完成的处理将作为下一个api的输入 如何在返回前在NodeJS中发出request.post调用以完成?我认为request.post是异步的,我需要使它同步。我试着使用回调,但没用 function abc(ip, op) { let options = { url: 'http://localhost:123/s', form: { ip

我必须按顺序进行多个RESTAPI Post调用。第一个REST api的输出,第一个api完成的处理将作为下一个api的输入

如何在返回前在NodeJS中发出request.post调用以完成?我认为request.post是异步的,我需要使它同步。我试着使用回调,但没用

function abc(ip, op) {
    let options = {
        url: 'http://localhost:123/s',
        form: {
            ipath: ip,
            opath: op
        }
    };
    request.post(options);
}
RESTAPI调用

app.post('/s', (req,res)=>{
    gm(img_path).implode(-1.2).write(op_path, function(err) {
        if (err)
            console.log(err);
    })
});

您不能同步执行,但您可以将其包装在一个Promise或use中,并使用/,以便在调用另一个函数之前等待abc的结果

const request = require('request-promise');

function abc(ip, op) {
    let options = {
        url: 'http://localhost:123/s',
        form: {
            ipath: ip,
            opath: op
        }
    };

    // This returns a promise when using request-promise
    return request.post(options);
}


async function myFunction() {

    const ip = ''; // Whatever ip / op are
    const op = '';

    const abcRes = await abc(ip, op);

    // This won't run until `abc` finishes
    const otherCallRes = await otherCall(abcRes);

    // Do something else with otherCallRes

    return otherCallRes;

}

myFunction()
  .then(console.log)
  .catch(console.error);

我是否也需要将abc作为异步函数?我收到错误“SyntaxError:await仅在异步函数中有效”,但我已将myFunction设置为异步。不,您不需要,因为您在abc中未使用await,我们只是返回一个承诺。您使用的是哪个节点版本?async/await从7.6开始提供。我给你的代码没有任何错误,除了没有定义otherCall之外。因此,请显示代码中出现错误的地方。@ashish1512那么,您在代码中找到错误了吗?非常感谢您的帮助!它起作用了!我使用了一个for-each循环,这就是它抛出错误的原因。我将其转换为for of循环。