NodeJS函数在预期之前返回

时间:2018-01-03 20:47:48

标签: node.js

我有一个循环并进行一些API调用的函数:

sendText(clientArr){
    clientArr.forEach(function (textObject, index) {
        var myRequest = {
            body: textObject.messageContent,
            to: { phoneNumber: textObject.phoneNumber },
            rules: ['sms']
        };

        var options = {
            method: 'POST',
            url: comapiUrl,
            headers:
                {
                    'cache-control': 'no-cache',
                    'content-type': 'application/json',
                    'accept': 'application/json',
                    authorization: 'Bearer ' + yourComapiAccessToken
                },
            body: myRequest,
            json: true
        };
        console.log('');
        console.log('Calling Comapi...');
        request(options, function (error, response, body) {
            if (error) throw new Error(error);

            console.log("HTTP status code returned: " + response.statusCode);

            // Check status
            if (response.statusCode == 201)
            {
                // All ok
                console.log('SMS message successfully sent via Comapi "One" API');
            }
            else
            {
                // Something went wrong
                console.log('Something went wrong!');
            }

            console.log(body);
            return response

        });
    })
};

此函数从此处调用:

function callAPI(req, res, apiMethod) {
let params = {};
params = req.params;
params.headers = req.headers;
if (req.method.toLowerCase() != 'get') {
    params.post = req.body;
}

params.query = req.query;
params.middlewareStorage = req.middlewareStorage;

apiMethod(params)
    .success(function (result) {
        res.send(result);
    })
    .failure(function (error) {
        console.logger.error(error);
        if (!(Object.prototype.toString.call(error) === '[object Object]')) {
            error = {success: false, error: error};
        }
        console.logger.error(error);
        res.status(500).send(error);
    });
}

路由器:

router.post('/sendText', function (req,res) {
    callAPI(req, res, fn.bind(apiObj, 'sendText'));
});

我得到的回应是:

POST / clients / sendText 500 320.615 ms - 1514 2018-01-04 02:03:38.887 DEBUG app - 返回HTTP状态码:201

返回500错误: 无法阅读财产的成功'未定义\ n在callAPI(

在我打算返回之前

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

sendText方法没有返回任何内容,因此undefined。因此,没有successfailure方法。但是,即使它返回有效的响应。响应应该有成功和失败的方法。

这里更好的方法是使用promises。您可以从api方法返回promise并更改callAPI方法以使用promise接口。

  

sendText方法(使用request-promise代替request

sendText(clientArr) {
    return Promise.all(clientArr.map(function (textObject, index) {
        var myRequest = {
            body: textObject.messageContent,
            to: { phoneNumber: textObject.phoneNumber },
            rules: ['sms']
        };

        var options = {
            method: 'POST',
            url: comapiUrl,
            headers:
                {
                    'cache-control': 'no-cache',
                    'content-type': 'application/json',
                    'accept': 'application/json',
                    authorization: 'Bearer ' + yourComapiAccessToken
                },
            body: myRequest,
            json: true,
            resolveWithFullResponse: true
        };
        console.log('');
        console.log('Calling Comapi...');
        return request(options)
        .then(function (response) {
            if (error) throw new Error(error);

            console.log("HTTP status code returned: " + response.statusCode);

            // Check status
            if (response.statusCode == 201)
            {
                // All ok
                console.log('SMS message successfully sent via Comapi "One" API');
            }
            else
            {
                // Something went wrong
                console.log('Something went wrong!');
            }

            console.log(body);
            return response
        });
    })
};
  

callApi

function callAPI(req, res, apiMethod) {
    let params = {};
    params = req.params;
    params.headers = req.headers;
    if (req.method.toLowerCase() != 'get') {
        params.post = req.body;
    }

    params.query = req.query;
    params.middlewareStorage = req.middlewareStorage;

    apiMethod(params)
    .then(function (result) {
        res.send(result);
    })
    .catch(function (error) {
        console.logger.error(error);
        if (!(Object.prototype.toString.call(error) === '[object Object]')) {
            error = {success: false, error: error};
        }
        console.logger.error(error);
        res.status(500).send(error);
    });
}