首页 > 解决方案 > 退出前等待响应

问题描述

我正在调用这个函数,它会将图像上传到 API 调用,然后它会返回一个远程图像的 url。

hash_image = putImageOnCloud(id_kromeda, filename)
        .then(
            (value) => {
                console.log('Immagine salvata in cloud: ' + value);
                process.exit(6);
            })
process.exit(5);
return hash_image;

但它以没有打印值的代码 5 退出;
所以我需要等待请求响应。我怎么能这样做?

async function putImageOnCloud(id_kromeda, filename) {

    filename = __dirname + '/../../public/images/' + filename;
    console.log('Salvo l\'immagine ' + filename + ' nel cloud.');

    let options = {
        'method': 'POST',
        'url': 'http://localhost/api/endpoint',
        'headers': {},
        formData: {
            'file': {
                'value': fs.createReadStream(filename),
                'options': {
                    'filename': '__.jpg',
                    'contentType': null
                }
            }
        }
    };
    request(options, function (error, response) {
        console.log('Faccio la call..')
        if (error) {
            throw new Error(error);
            process.exit(4);
        }
        console.log(response.body);
        let risposta = JSON.parse(response.body);
        /*
        [
          {
            "file_url": "http://localhost/a6e10970-c492-42f7-bc0d-965d28be7d2b.jpg",
            "_id": "a6e10970-c492-42f7-bc0d-965d28be7d2b.jpg"
          }
        ]
         */
        let image_cdn = risposta[0]._id; // file_url

        console.log('[' + id_kromeda + '] Salvato immagine in cloud: ' + image_cdn);
        return image_cdn;
    });
}

标签: node.jsasynchronous

解决方案


推荐阅读